python - 当使用使用夏令时的 Python 时区时,应该传递什么 tzinfo?

标签 python datetime dst timezone-offset

我正在尝试将日期字符串转换为日期时间,但找不到任何涉及哪些时区代码映射到哪些时区的可靠文档,特别是我正在处理利用夏令时的时区。

我有 4 个潜在的时区代码,我正在尝试确定将哪些内容传递给 tz.gettz 作为夏令时代码。

import dateutil.parser as p
import dateutil.tz as tz

tzinfos = {"CST": tz.gettz("America/Chicago"),
           "CDT": tz.gettz("?"),                # HERE
           "EST": tz.gettz("America/Eastern"),
           "EDT": tz.gettz("?")                 # HERE
           }

date_strings = ["Wed Mar 03 09:44:59 CST 2021",
                "Wed Mar 03 09:44:59 CDT 2021",
                "Wed Mar 03 09:44:59 EST 2021",
                "Wed Mar 03 09:44:59 EDT 2021"]

for s in date_strings:
    print(p.parse(s, tzinfos=tzinfos))

日期字符串是通过我所在州交通部提供的 API 传入的,该 API 从州高速公路内置的传感器获取数据,最终目标是将它们全部转换为 UTC 时间,但我没有办法知道他们的 UTC 时间应该,所以我不能只是猜测时区然后验证它们。

我一直在经历this wikipedia page of timezones 例如,CDT 似乎与 CST 相同,为 tz.gettz("America/Chicago"),但我正在处理的应用程序将用于 dispatch 急救人员应对交通事故,因此正确处理时间转换至关重要。我希望找到有关应传递给 tz.gettz() 函数的内容的文档?

最佳答案

查看dateutil.tz的文档:

help(dateutil.tz)
...
     |  Using the US Eastern time zone as an example, we can see that a ``tzfile``
     |  provides time zone information for the standard Daylight Saving offsets:
     |  
     |  .. testsetup:: tzfile
     |  
     |      from dateutil.tz import gettz
     |      from datetime import datetime
     |  
     |  .. doctest:: tzfile
     |  
     |      >>> NYC = gettz('America/New_York')
     |      >>> NYC
     |      tzfile('/usr/share/zoneinfo/America/New_York')
     |  
     |      >>> print(datetime(2016, 1, 3, tzinfo=NYC))     # EST
     |      2016-01-03 00:00:00-05:00
     |  
     |      >>> print(datetime(2016, 7, 7, tzinfo=NYC))     # EDT
     |      2016-07-07 00:00:00-04:00
...

Time zones account for daylight savings time offsets according to the date, automatically. So your tzinfos should be:

tzinfos = {"CST": tz.gettz("America/Chicago"),
           "CDT": tz.gettz("America/Chicago"),                
           "EST": tz.gettz("America/Eastern"),
           "EDT": tz.gettz("America/Eastern")                 
           }

真的花时间阅读整个文档,它非常简洁。 “America/New_York”时区甚至在二战期间也采用全年夏令时。

关于python - 当使用使用夏令时的 Python 时区时,应该传递什么 tzinfo?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66718240/

相关文章:

python - 三层嵌套字典的存在性检验

python - 在 Python 中返回一个 ping 测试结果

python - R中有z.fill函数吗

python - Python 中的静态代码分析?

java - 在 Spring 根据请求设置时区

mysql - 在两个 td 标签中显示日期时间

ruby-on-rails - 在给定 UTC 偏移量和 DST 的情况下自动检测 Rails 中的时区

php - javascript错误地确定了夏令时线(2006年的示例)

c# - 日期时间比较和夏令时/其他奇怪之处

python - 自动在文件夹中创建文件(Python)