简体   繁体   English

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

[英]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 UTC

2010-05-11 17:07:33 EDT 2010-05-11 17:07:33美国东部时间

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 我得到的问题是EDT无法识别,具体错误是

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. 查看pytz世界时区定义库。

This library allows accurate and cross platform timezone calculations using Python 2.3 or higher. 该库允许使用Python 2.3或更高版本进行准确的跨平台时区计算。 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). 它还解决了夏令时结束时模糊时间的问题,您可以在Python库参考(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). 它利用了tz数据库 ,它应该包含EDT,并允许您执行所需的计算(并且可能比您当前的实现更可靠和准确)。

In addition to pytz , check out python-dateutil . 除了pytz ,请查看python-dateutil The relativedelta functionality is outstanding. relativedelta功能非常出色。

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 来自strptime的文档

Support for the %Z directive is based on the values contained in tzname and whether daylight is true. 对%Z指令的支持基于tzname中包含的值以及日光是否为真。 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). 因此,它是特定于平台的,除了识别始终已知的UTC和GMT(并且被认为是非夏令时时区)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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