datetime: get timestamp with timezone offset

戏子无情 提交于 2020-12-13 03:12:57

问题


I would like to get the timestamp from dates in the following formats:

Mon, 23 Nov 2020 19:00:00 GMT
Mon, 23 Nov 2020 20:00:00 +0100

I am using the the following statements to convert dates to datetime objects:

dateobj = datetime.datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %Z')
dateobj = datetime.datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %z')

But using .timestamp() method, different seconds from epoch are printed. Why doesn't the %Z directive add timezone information to the datetime object? How could I get the timezone into account, so the timestamp is equal?


回答1:


Please note Inconsistent datetime parse timezone in Python. Your problem is %Z, it makes strptime accept certain strings (GMT, UTC and any value in time.tzname - docs), but doesn't actually make anything out of it. The returned datetime object is naive - which is why Python will assume it's local time if you call the timestamp() method of it.

You can use dateutil's parser instead:

from dateutil.parser import parse

for s in ("Mon, 23 Nov 2020 19:00:00 GMT", "Mon, 23 Nov 2020 20:00:00 +0100"):
    dt = parse(s)
    print(repr(dt), dt.timestamp())

# datetime.datetime(2020, 11, 23, 19, 0, tzinfo=tzutc()) 1606158000.0
# datetime.datetime(2020, 11, 23, 20, 0, tzinfo=tzoffset(None, 3600)) 1606158000.0


来源:https://stackoverflow.com/questions/64975698/datetime-get-timestamp-with-timezone-offset

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