为什么 PST (America/Los_Angeles) 时间转换为 UTC 时差 1 小时?

Why is PST (America/Los_Angeles) time conversion to UTC, 1 hour behind?

我的传感器数据的时间戳已知为 PST(太平洋标准时间)。假设时间戳是:2020-10-21 10:00:00。我想将该时间戳转换为 UTC。 UTC 到 PST 的转换是 UTC-8。所以 UTC 中的 expected 时间戳向前 8 小时:2020-10-21 18:00:00.

我尝试进行转换:

>>> import pytz
>>> from datetime import datetime
>>> ts = datetime(2020,10,21,10,0,0)
>>> ts_local = pytz.timezone('America/Los_Angeles').localize(ts, is_dst=False)
>>> ts_local.strftime('%Y-%m-%d %H:%M:%S %Z%z')
'2020-10-21 10:00:00 PDT-0700'
>>> ts_local.astimezone(pytz.utc).strftime('%Y-%m-%d %H:%M:%S %Z%z')
'2020-10-21 17:00:00 UTC+0000'

但是您可以看到转换比预期晚了 1 小时。这似乎是有道理的,因为 ts_local 似乎在 PDT 中。但是,因为我设置了 is_dst=False,所以我希望 ts_localPST.

我已经阅读了一些关于如何进行转换的其他 SO 答案,我所做的就是建议的内容。

根据问题中提供的信息,对我来说,设置 时区 (有 DST 更改!)是错误的方法,如果你只是有一个固定的偏移量数据中 x 小时的 UTC。这假定您的传感器的时钟没有将 DST 更改编码到其内存中。

因此我的建议是使用固定偏移量 tzinfo:

from datetime import datetime, timedelta, timezone

dt = datetime.fromisoformat("2020-10-21 10:00:00")

# we know dt is UTC-8, so you can set the fixed offset:
dt_tzset = dt.replace(tzinfo=timezone(timedelta(hours=-8)))

# now you can convert to UTC easily:
dt_utc = dt_tzset.astimezone(timezone.utc)
print(dt_utc)
# 2020-10-21 18:00:00+00:00

来自the pytz docs

The is_dst parameter is ignored for most timestamps. It is only used during DST transition ambiguous periods to resolve that ambiguity.

America/Los_Angeles中没有关于2020-10-21 18:00:00的歧义。它是明确的 UTC-7 (PDT)。

America/Los_Angeles 中时间戳不明确的一个示例是 2020-11-01 01:00:00,因为由于 DST fall-back 转换,其中有两个。第一个是 01:00 PDT,第二个是 01:00 PST。