pytz utc conversion
将天真的时间和
说我有:
1 2 | d = datetime(2009, 8, 31, 22, 30, 30) tz = timezone('US/Pacific') |
pytz的第一种方式是:
1 2 3 | d_tz = tz.normalize(tz.localize(d)) utc = pytz.timezone('UTC') d_utc = d_tz.astimezone(utc) |
第二种方式,来自UTCDateTimeField
1 2 3 4 5 6 7 8 9 10 11 | 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) |
不用说这两种方法在相当多个时区上会产生不同的结果。
问题是-正确的方法是什么?
您的第一种方法似乎是已批准的方法,并且应支持DST。
您可以将其缩短一点,因为pytz.utc = pytz.timezone('UTC'),但是您已经知道了:)
1 2 3 4 5 | 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()) |
What is the right way to convert a naive time and a tzinfo into an utc time?
此答案列举了将本地时间转换为UTC的一些问题:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | from datetime import datetime import pytz # $ pip install pytz d = datetime(2009, 8, 31, 22, 30, 30) tz = pytz.timezone('US/Pacific') # a) raise exception for non-existent or ambiguous times aware_d = tz.localize(d, is_dst=None) ## b) assume standard time, adjust non-existent times #aware_d = tz.normalize(tz.localize(d, is_dst=False)) ## c) assume DST is in effect, adjust non-existent times #aware_d = tz.normalize(tz.localize(naive_d, is_dst=True)) # convert to UTC utc_d = aware_d.astimezone(pytz.utc) |
使用第一种方法。 没有理由重新发明时区转换的轮子
1 2 3 4 5 | import pytz from django.utils import timezone tz = pytz.timezone('America/Los_Angeles') time = tz.normalize(timezone.now()) |