How to find the difference between times in different time zones in Python?

I am trying to calculate the difference (in seconds) between two dates / time formats as follows:

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 received is that the EDT is not recognized, a special error

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

Check out pytz at the world time zone definition library.

- Python 2.3 . , Python (datetime.tzinfo).

tz database, EDT, , (, , , ).

+8

pytz, python-dateutil. relativedelta .

:

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)
+10

strptime

Support for the% Z directive is based on the values ​​contained in tzname and whether daylight is true. Because of this, it depends on the platform, except for the recognition of UTC and GMT, which are always known (and are considered not related to daylight saving time).

0
source

All Articles