我正在编写一些需要处理时区的Python(Python 2.7.4(默认,2013年4月6日,19:54:46)[MSC v.1500 32位(Intel)] on win32,Windows 7)代码。为此,我使用 pytz 库(2012d 版本),为了安全起见,我刚刚使用 easy_install 更新了该库。
我特别需要表达中国四川省成都市的 express 时间。这是“亚洲/重庆”时区,应该比“欧洲/伦敦”(这是我本地的时区)早 +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
最佳答案
您需要使用.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 :
Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones.
经过此更改,输出变为:
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
请注意,纽约偏移量也不正确。
关于python - pytz.timezone ('Asia/Chongqing' )行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16916418/