pytz UTC 转换
将简单时间和 tzinfo 转换为 UTC 时间的正确方法是什么? 假设我有:
d = datetime(2009, 8, 31, 22, 30, 30)
tz = timezone('US/Pacific')
第一种方式,受 pytz 启发:
d_tz = tz.normalize(tz.localize(d))
utc = pytz.timezone('UTC')
d_utc = d_tz.astimezone(utc)
第二种方式,来自 UTCDateTimeField
def utc_from_localtime(dt, tz):
dt = dt.replace(tzinfo=tz)
_dt = tz.normalize(dt)
if dt.tzinfo != _dt.tzinfo:
# Houston, we have a problem...
# find out which one has a dst offset
if _dt.tzinfo.dst(_dt):
_dt -= _dt.tzinfo.dst(_dt)
else:
_dt += dt.tzinfo.dst(dt)
return _dt.astimezone(pytz.utc)
不用说这两种方法对相当多的时区产生不同的结果。
问题是 - 什么是正确的方法?
What is the right way to convert a naive time and a tzinfo
into an UTC time?
Say I have:
d = datetime(2009, 8, 31, 22, 30, 30)
tz = timezone('US/Pacific')
First way, pytz inspired:
d_tz = tz.normalize(tz.localize(d))
utc = pytz.timezone('UTC')
d_utc = d_tz.astimezone(utc)
Second way, from UTCDateTimeField
def utc_from_localtime(dt, tz):
dt = dt.replace(tzinfo=tz)
_dt = tz.normalize(dt)
if dt.tzinfo != _dt.tzinfo:
# Houston, we have a problem...
# find out which one has a dst offset
if _dt.tzinfo.dst(_dt):
_dt -= _dt.tzinfo.dst(_dt)
else:
_dt += dt.tzinfo.dst(dt)
return _dt.astimezone(pytz.utc)
Needless to say those two methods produce different results for quite a few timezones.
Question is - what's the right way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的第一个方法似乎是已批准的方法,并且应该了解 DST。
您可以稍微缩短它,因为 pytz.utc = pytz.timezone('UTC'),但您已经知道了:)
Your first method seems to be the approved one, and should be DST-aware.
You could shorten it a tiny bit, since pytz.utc = pytz.timezone('UTC'), but you knew that already :)
此答案列举了将本地时间转换为 UTC 的一些问题:
This answer enumerates some issues with converting a local time to UTC:
使用第一种方法。没有理由重新发明时区转换的轮子
Use the first method. There's no reason to reinvent the wheel of timezone conversion