【问题标题】:pytz.timezone('Asia/Chongqing') is behaving strangelypytz.timezone('Asia/Chongqing') 行为异常
【发布时间】:2013-05-30 18:22:20
【问题描述】:

我正在编写一些需要处理时区的 Python(Python 2.7.4(默认,2013 年 4 月 6 日,19:54:46)[MSC v.1500 32 位(英特尔)] on win32,Windows 7)代码。为此,我正在使用 pytz 库(2012d 版本),为了安全起见,我刚刚使用 easy_install 进行了更新。

我特别需要表达中国四川省成都的时间。这是在“亚洲/重庆”时区,应该比“欧洲/伦敦”(我的本地时区)早 +07:00 小时

由于某种原因,当我在“亚洲/重庆”区域创建 datetime.datetime 时,应用的偏移量是 +07:06 而不是我期望的 +07:00。但是当我在另一个区域(比如纽约)创建 datetime.datetime 时,它​​可以正常工作。

我认为 pytz 数据库是正确的,那么我做错了什么?如有任何建议,我将不胜感激。

"""
Fragment of code for messing about with (foreign)
time-zones and datetime/ephem
"""

import datetime
import pytz

ChengduTZ = pytz.timezone('Asia/Chongqing')
ParisTZ   = pytz.timezone('Europe/Paris')
LondonTZ  = pytz.timezone('Europe/London')
NewYorkTZ = pytz.timezone('America/New_York')

MidnightInChengdu = datetime.datetime(2013, 6, 5, 0, 0, 0, 0, ChengduTZ)
MidnightInNewYork = datetime.datetime(2013, 6, 5, 0, 0, 0, 0, NewYorkTZ)

print("When it's midnight in Chengdu it's:")
print(MidnightInChengdu)
print(MidnightInChengdu.astimezone(LondonTZ))
print(MidnightInChengdu.astimezone(ParisTZ))
print(MidnightInChengdu.astimezone(NewYorkTZ))

print("\nWhen it's midnight in New York it's:")
print(MidnightInNewYork)
print(MidnightInNewYork.astimezone(LondonTZ))
print(MidnightInNewYork.astimezone(ParisTZ))
print(MidnightInNewYork.astimezone(ChengduTZ))

产生以下输出:

When it's midnight in Chengdu it's:
2013-06-05 00:00:00+07:06
2013-06-04 17:54:00+01:00
2013-06-04 18:54:00+02:00
2013-06-04 12:54:00-04:00

When it's midnight in New York it's:
2013-06-05 00:00:00-05:00
2013-06-05 06:00:00+01:00
2013-06-05 07:00:00+02:00
2013-06-05 13:00:00+08:00

【问题讨论】:

标签: python datetime timezone pytz


【解决方案1】:

您需要使用.localize()方法将日期时间放入正确的时区,否则会错误选择历史偏移量:

ChengduTZ = pytz.timezone('Asia/Chongqing')
MidnightInChengdu = ChengduTZ.localize(datetime.datetime(2013, 6, 5, 0, 0, 0, 0))
MidnightInNewYork = NewYorkTZ.localize(datetime.datetime(2013, 6, 5, 0, 0, 0, 0))

pytz documenation

不幸的是,在许多时区使用标准日期时间构造函数的 tzinfo 参数“不起作用”。

有了这个改变,输出变成:

When it's midnight in Chengdu it's:
2013-06-05 00:00:00+08:00
2013-06-04 17:00:00+01:00
2013-06-04 18:00:00+02:00
2013-06-04 12:00:00-04:00

When it's midnight in New York it's:
2013-06-05 00:00:00-04:00
2013-06-05 05:00:00+01:00
2013-06-05 06:00:00+02:00
2013-06-05 12:00:00+08:00

请注意,纽约的偏移量也不正确。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 2017-01-22
    • 2013-04-14
    • 2014-01-29
    • 1970-01-01
    • 2011-01-13
    • 2010-10-14
    相关资源
    最近更新 更多