如何在Python中找到不同时区的时间之间的差异?

如何在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 UTC

2010-05-11 17:07:33 EDT

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

我得到的问题是EDT无法识别,具体错误是

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'


查看 pytz 世界时区定义库。

Check out the pytz world timezone definitions library.


该库允许使用Python 2.3或更高版本进行准确的跨平台时区计算。它还解决了夏令时结束时时间模糊的问题,您可以在Python库参考(datetime.tzinfo)中了解更多信息。

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

它利用 tz数据库 的优势应该包括EDT,并允许您执行所需的计算(并且可能比当前的实现更可靠,更准确)。

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