在Python中将时区偏移量应用于日期时间 [英] Apply timezone offset to datetime in Python

查看:111
本文介绍了在Python中将时区偏移量应用于日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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")

返回

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

我不敢相信datetimepandas中没有方法将与时区相关的偏移量应用于日期时间并返回纯UTC日期时间.

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.

如何应用tzinfo偏移量/增量,以使所得时区为普通UTC(tzinfo=None)?

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

推荐答案

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

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)

这篇关于在Python中将时区偏移量应用于日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆