简体   繁体   中英

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'

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM