在tz无意识时间,UTC和在python中使用时区之间正确转换

时间:2011-09-27 00:20:27

标签: python pytz

我有一个'20111014T090000'形式的字符串,带有相关的时区ID(TZID = America / Los_Angeles),我想要 使用适当的偏移量将其转换为UTC时间(以秒为单位)。

问题似乎是我的输出时间关闭了1小时(它应该是PST时应该是PDT)而我正在使用pytz来帮助timezo

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 :(得分: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方法。

答案 1 :(得分:0)

编写

simple-date是为了使转换变得像这样微不足道(你需要版本0.2.1或更高版本):

>>> from simpledate import *
>>> SimpleDate('20111014T090000', tz='America/Los_Angeles').timestamp
1318608000.0

答案 2 :(得分: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。

答案 3 :(得分:0)

将给定字符串转换为天真的日期时间对象:

>>> from datetime import datetime
>>> naive_dt = datetime.strptime('20111014T090000', '%Y%m%dT%H%M%S')
>>> naive_dt
datetime.datetime(2011, 10, 14, 9, 0)

附加时区(使其成为知晓的日期时间对象):

>>> import pytz
>>> tz = pytz.timezone('America/Los_Angeles')
>>> local_dt = tz.localize(naive_dt, is_dst=None)
>>> print(local_dt.strftime("%Y-%m-%d %H:%M:%S %Z%z"))
2011-10-14 09:00:00 PDT-0700

注意:is_dst=None用于针对不存在或模糊的本地时间引发异常。

从知道的datetime对象获取POSIX时间戳:

>>> (local_dt - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
1318608000.0

您问题中的主要问题是:

  1. 您替换tzinfo属性,而应使用tz.localize
  2. mktime()适用于当地时间(您的计算机时区),而非UTC。
相关问题