我的传感器数据的时间戳已知为 PST(太平洋标准时间)。假设时间戳为:2020-10-21 10:00:00
。我想将该时间戳转换为 UTC。 UTC 到 PST 的转换为 UTC-8。因此,预期 UTC 时间戳向前 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_local
采用 PST
。
- 我尝试过
is_dst=True
和is_dst=None
(尽管这些标志值没有意义,因为时间戳采用标准时间),但结果ts_local
保留在PDT
中。 - 我已在 Python 3.7.4 和 Python 2.7.17 中尝试过这种转换,并得到了相同的结果。
- 我也尝试过使用
'US/Pacific'
pytz 时区进行此转换,但遇到了同样的问题。
我已经阅读了一些其他关于如何进行转换的答案,我所做的就是建议的。
最佳答案
根据问题中提供的信息,对我来说,如果您只是在 UTC 之间有 x 小时的固定偏移,那么设置时区(具有 DST 更改!)是错误的方法。您的数据。这假设您的传感器时钟没有将 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
关于python - 为什么 PST(美国/洛杉矶)时间转换为 UTC 时间晚 1 小时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64470680/