Apply timezone offset to datetime in Python

风格不统一 提交于 2019-12-02 05:20:27

问题


For a given date string such as 2009-01-01T12:00:00+0100 I want the UTC datetime object.

from datetime import datetime 
datetime.strptime("2013-03-21T14:19:42+0100", "%Y-%m-%dT%H:%M:%S%z")

returns

datetime.datetime(2013, 3, 21, 14, 19, 42, tzinfo=datetime.timezone(datetime.timedelta(0, 3600)))

I cannot believe there is no method in datetime or pandas for applying the timezone-related offset to the datetime and returning plain UTC datetime.

How can I apply the tzinfo offset/delta, so that the resulting timezone is plain UTC (tzinfo=None)?


回答1:


This feels a bit dirty but it does work

from datetime import datetime
orig_dt = datetime.strptime("2013-03-21T14:19:42+0100", "%Y-%m-%dT%H:%M:%S%z")  # datetime.datetime(2013, 3, 21, 14, 19, 42, tzinfo=datetime.timezone(datetime.timedelta(0, 3600)))
utc_time_value = orig_dt - orig_dt.utcoffset()
utc_dt = utc_time_value.replace(tzinfo=None)  # datetime.datetime(2013, 3, 21, 13, 19, 42)


来源:https://stackoverflow.com/questions/52371705/apply-timezone-offset-to-datetime-in-python

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