pytz.时区(亚洲/重庆)的行为很奇怪

2024-04-18 21:30:26 发布

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

我正在写一些Python(Python 2.7.4(默认值,2013年4月6日,19:54:46)[mscv.1500 32位(Intel)]在win32,windows7上)代码,它需要处理时区。为此,我正在使用pytz库(2012d版本),为了安全起见,我刚刚用easy-install更新了它。在

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

当我创建一个日期时间。日期时间在'Asia/Chonqing'区域,应用的偏移量是+07:06,而不是我预期的+07:00。但是当我创建一个日期时间。日期时间在另一个区域(比如说纽约)它可以正常工作。在

我假设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))

生成以下输出:

^{pr2}$

Tags: 区域datetime时间itprinttimezonepytzasia
1条回答
网友
1楼 · 发布于 2024-04-18 21:30:26

您需要使用.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))

参见^{} documenation

Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones.

通过此更改,输出变成:

^{pr2}$

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

相关问题 更多 >