JasonA
JasonA

Reputation: 147

How do I find difference between times in different timezones in Python?

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'

Upvotes: 5

Views: 6446

Answers (3)

iondiode
iondiode

Reputation: 650

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).

Upvotes: 0

Hank Gay
Hank Gay

Reputation: 72039

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)

Upvotes: 5

Dolph
Dolph

Reputation: 50710

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).

Upvotes: 8

Related Questions