Python似乎错误地处理了时区转换

时间:2015-07-24 01:12:13

标签: python time timezone

我对python程序中的以下行为感到困惑,我正在编写转换日期和时间。我有原始“挂钟时间”的数据作为新西兰标准时间,并希望将其转换为始终为UTC + 12(或pytz中提供的GMT + 12)。

问题在于,当我运行程序时,它会给出看起来不正确的结果。示例输出如下所示。当输入日期为24/07/2015 08:00(2015年7月24日上午8点)时,定义为“太平洋/奥克兰”,然后转换为GMT + 12,它似乎提供了一天前的错误结果。我不知道为什么会这样,因为如果我对时区转换的理解是正确的,时间应该完全相同。

有人能指出我在这里做错了吗?

节目输出:

Pacific/Auckland
24/07/2015 08:00
23/07/2015 08:00

“最小工作示例”源代码:

#!/usr/bin/env python

import time
import pytz
import datetime

def main():

    time_zone = 'Pacific/Auckland'
    print(time_zone)

    local = pytz.timezone(time_zone)

    time_str = '24/07/2015 08:00'
    print(time_str)

    t = time.strptime(time_str, '%d/%m/%Y %H:%M')
    t_datetime = datetime.datetime.fromtimestamp(time.mktime(t))

    local_dt = local.localize(t_datetime)

    ds2 = local_dt.astimezone(pytz.timezone('Etc/GMT+12')).strftime('%d/%m/%Y %H:%M')

    print(ds2)


if __name__ == '__main__':
    # Parse the system arguments and get the busbar and input directory.
    main()

##### END OF FILE #####

1 个答案:

答案 0 :(得分:2)

POSIX style timezones ('Etc/GMT+h') have the opposite sign。您将从+1200转换为-1200,这总共需要24小时,这就是为什么您会在相同的时间但是错误的一天。

#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz

naive = datetime.strptime('24/07/2015 08:00', '%d/%m/%Y %H:%M')
aware = pytz.timezone('Pacific/Auckland').localize(naive, is_dst=None)
print(aware)
utc_dt = aware.astimezone(pytz.utc)
print(utc_dt)
# +1200
print(utc_dt.astimezone(pytz.timezone('Etc/GMT-12')))

输出

2015-07-24 08:00:00+12:00
2015-07-23 20:00:00+00:00
2015-07-24 08:00:00+12:00