views:

80

answers:

3

I am trying to calculate difference(in seconds) between two date/times formatted as following:

2010-05-11 17:07:33 UTC

2010-05-11 17:07:33 EDT

time1 = '2010-05-11 17:07:33 UTC'
time2 = '2010-05-11 17:07:33 EDT'
delta = time.mktime(time.strptime(time1,"%Y-%m-%d %H:%M:%S %Z"))-\
        time.mktime(time.strptime(time2, "%Y-%m-%d %H:%M:%S %Z"))

The problem I got is EDT is not recognized, the specific error is

ValueError: time data '2010-05-11 17:07:33 EDT' does not match format '%Y-%m-%d %H:%M:%S %Z'
+5  A: 

Check out the pytz world timezone definitions library.

This library allows accurate and cross platform timezone calculations using Python 2.3 or higher. It also solves the issue of ambiguous times at the end of daylight savings, which you can read more about in the Python Library Reference (datetime.tzinfo).

It takes advantage of the tz database, which should include EDT, and allow you to perform the calculations you need to (and probably more reliably & accurately than your current implementation).

Dolph
+1 because `pytz` is the bee's knees.
jathanism
A: 

From docs for strptime

Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).

iondiode
+2  A: 

In addition to pytz, check out python-dateutil. The relativedelta functionality is outstanding.

Here's a sample of using them together:

from datetime import datetime

from dateutil.relativedelta import *
import pytz

if __name__ == '__main__':
    date_one = datetime.now(pytz.timezone('US/Eastern'))
    date_two = datetime.now(pytz.timezone('US/Mountain'))
    rdelta = relativedelta(date_one, date_two)
    print(rdelta)
Hank Gay