pytz utc转换 [英] pytz utc conversion
本文介绍了pytz utc转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将天真时间和 tzinfo
转换为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')
首先,pytz启发:
First way, pytz inspired:
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)
不用说这两种方法产生不同的结果
Needless to say those two methods produce different results for quite a few timezones.
问题是 - 正确的方法是什么?
Question is - what's the right way?
推荐答案
您的第一种方法似乎是被批准的方法,应该是DST感知的。
Your first method seems to be the approved one, and should be DST-aware.
自从pyz以后,您可以缩短一点。 utc = pytz.timezone('UTC'),但你知道已经:)
You could shorten it a tiny bit, since pytz.utc = pytz.timezone('UTC'), but you knew that already :)
tz = timezone('US/Pacific')
def toUTC(d):
return tz.normalize(tz.localize(d)).astimezone(pytz.utc)
print "Test: ", datetime.datetime.utcnow(), " = ", toUTC(datetime.datetime.now())
这篇关于pytz utc转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文