我使用pytz模块将America / Los_Angeles时区的日期转换为utc,代码如下:
TZ = 'America/Los_Angeles'
from = pytz.timezone(TZ)
utc = from.localize(original_date).astimezone(pytz.utc)
现在,我想测试utc值是否实际上是UTC格式。如何用pytz或datetime做到这一点?
请帮助 谢谢
答案 0 :(得分:6)
utc.tzinfo == pytz.utc # returns True if utc in UTC
示例:
now = datetime.datetime.now(pytz.utc)
now.tzinfo == pytz.utc # returns True
now = now.astimezone(pytz.timezone('America/Los_Angeles'))
now.tzinfo == pytz.utc # returns False
答案 1 :(得分:1)
接受的答案不适用于pytz
对象。由于pytz
实际上很难进行转换[1](例如正确执行夏令时等),因此最好进行交叉实现检查。
now = datetime.datetime.now(pytz.utc)
if now.tzinfo:
now.utcoffset().total_seconds() == 0 # returns true
[1] https://pendulum.eustace.io/blog/a-faster-alternative-to-pyz.html