在Python中正确转换无时区时间、UTC及处理时区
我有一个字符串,格式是 '20111014T090000',还有一个时区ID(TZID=America/Los_Angeles),我想把它转换成UTC时间的秒数,并且要加上合适的时差。
问题是我的输出时间比实际时间少了1个小时(它显示的是太平洋标准时间PST,而应该是太平洋夏令时间PDT),我正在使用pytz来处理时区。
import pytz
def convert_to_utc(date_time)
# date_time set to '2011-10-14 09:00:00' and is initially unaware of timezone information
timezone_id = 'America/Los_Angeles'
tz = pytz.timezone(timezone_id);
# attach the timezone
date_time = date_time.replace(tzinfo=tz);
print("replaced: %s" % date_time);
# this makes date_time to be: 2011-10-14 09:00:00-08:00
# even though the offset should be -7 at the present time
print("tzname: %s" % date_time.tzname());
# tzname reports PST when it should be PDT
print("timetz: %s" % date_time.timetz());
# timetz: 09:00:00-08:00 - expecting offset -7
date_time_ms = int(time.mktime(date_time.utctimetuple()));
# returns '1318611600' which is
# GMT: Fri, 14 Oct 2011 17:00:00 GMT
# Local: Fri Oct 14 2011 10:00:00 GMT-7
# when expecting: '1318608000' seconds, which is
# GMT: Fri, 14 Oct 2011 16:00:00 GMT
# Local: Fri Oct 14 2011 9:00:00 GMT-7 -- expected value
我该如何根据时区ID获取正确的时差呢?
4 个回答
0
如果在你的程序中暂时可以更改全局时区,你也可以这样做:
os.environ['TZ'] = 'America/Los_Angeles'
t = [2011, 10, 14, 9, 0, 0, 0, 0, -1]
return time.mktime(time.struct_time(t))
这样会返回预期的结果1318608000.0。
0
simple-date 这个工具是为了让像这样的日期转换变得非常简单的(你需要使用0.2.1或更高版本才能实现这个功能):
>>> from simpledate import *
>>> SimpleDate('20111014T090000', tz='America/Los_Angeles').timestamp
1318608000.0
3
下面这段代码可以实现你想要的功能。
def convert(dte, fromZone, toZone):
fromZone, toZone = pytz.timezone(fromZone), pytz.timezone(toZone)
return fromZone.localize(dte, is_dst=True).astimezone(toZone)
这里最重要的是要把 is_dst
这个参数传递给 localize 方法。