Checking if date is in UTC format

眉间皱痕 提交于 2020-07-06 23:25:52

问题


Im using the pytz module to translate a date in America/Los_Angeles timezone to utc by the code below :

TZ = 'America/Los_Angeles'
from = pytz.timezone(TZ)
utc = from.localize(original_date).astimezone(pytz.utc)

Now,i want to test if utc value is actually in UTC format or not. How to do that with pytz or datetime ?

Please Help Thank You


回答1:


utc.tzinfo == pytz.utc # returns True if utc in UTC

Example:

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



回答2:


The accepted answer will not work for anything else as pytz objects. As pytz is actually pretty bad at doing conversions[1] (e.g. properly doing daylight savings etc) it is probably better to do a cross-implementation check.

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



来源:https://stackoverflow.com/questions/6706499/checking-if-date-is-in-utc-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!