在不知道tz的时间、UTC和在python中使用时区之间正确转换

2024-09-29 21:40:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个格式为'20111014t09000'的字符串,带有相关的时区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获取正确的偏移量?在


Tags: thetodatetimeisbeoctprint
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方法。在

编写simple-date是为了使转换变得如此简单(您需要0.2.1或更高版本才能完成此操作):

>>> from simpledate import *
>>> SimpleDate('20111014T090000', tz='America/Los_Angeles').timestamp
1318608000.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。在

相关问题 更多 >

    热门问题