如何确定适用于 python3 给定区域历史日期的时区

How to determine the appropriate the timezone to apply for historical dates in a give region in python3

我在 Ubuntu 20.04 使用 python3。

我有一大堆文件,其中包含简单的日期时间字符串,可以追溯到 20 多年前。我知道所有这些日期时间都在太平洋时区。我想将它们全部转换为 UTC 日期时间。

但是,它们是相对于 PDT 还是 PST 是一个更大的问题。由于在过去 20 年中 PDT/PST 变化发生了变化,因此不仅仅是做一个简单的 date/month 阈值来确定是应用 pdt 还是 pst 时区。有没有一种优雅的方法来做出这个决定并应用它?

您可以按照以下步骤设置时区并转换为 UTC。 dateutil will take DST changes from the IANA database.

from datetime import datetime
import dateutil

datestrings = ['1991-04-06T00:00:00', # PST
               '1991-04-07T04:00:00', # PDT
               '1999-10-30T00:00:00', # PDT
               '1999-10-31T02:01:00', # PST
               '2012-03-11T00:00:00', # PST
               '2012-03-11T02:00:00'] # PDT

# to naive datetime objects
dateobj = [datetime.fromisoformat(s) for s in datestrings]

# set timezone:
tz_pacific = dateutil.tz.gettz('US/Pacific')
dtaware = [d.replace(tzinfo=tz_pacific) for d in dateobj] 
# with pytz use localize() instead of replace

# check if has DST:
# for d in dtaware: print(d.dst())
# 0:00:00
# 1:00:00
# 1:00:00
# 0:00:00
# 0:00:00
# 1:00:00

# convert to UTC:
dtutc = [d.astimezone(dateutil.tz.UTC) for d in dtaware]

# check output
# for d in dtutc: print(d.isoformat())
# 1991-04-06T08:00:00+00:00
# 1991-04-07T11:00:00+00:00
# 1999-10-30T07:00:00+00:00
# 1999-10-31T10:01:00+00:00
# 2012-03-11T08:00:00+00:00
# 2012-03-11T09:00:00+00:00

现在,如果您想绝对确定 DST(PDT 与 PST)设置是否正确,我想您必须设置测试用例并根据 IANA 进行验证...