在Python中将时区偏移应用于日期时间

问题描述 投票:1回答:1

对于给定的日期字符串,例如2009-01-01T12:00:00+0100,我想要UTC日期时间对象。

from datetime import datetime 
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)))

我无法相信datetimepandas中没有方法将时区相关偏移应用于日期时间并返回纯UTC日期时间。

如何应用tzinfo偏移量/ delta,以便生成的时区为纯UTC(tzinfo=None)?

python pandas datetime timezone timezone-offset
1个回答
3
投票

这感觉有点脏,但确实有效

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)
© www.soinside.com 2019 - 2024. All rights reserved.