Вопрос

I am writing some Python (Python 2.7.4 (default, Apr 6 2013, 19:54:46) [MSC v.1500 32 bit (Intel)] on win32, Windows 7) code which needs to handle timezones. For this I am using the pytz library (2012d version) which to be on the safe-side I've just updated using easy_install.

I specifically need to express times in Chengdu, Sichuan province, PRC. This is in the 'Asia/Chongqing' timezone which should be +07:00 hours ahead of 'Europe/London' (which is my local timezone)

For some reason when I create a datetime.datetime in the 'Asia/Chonqing' zone the offset applied is +07:06 not the +07:00 I would expect. But when I create a datetime.datetime in another zone (New York, say) it works OK.

I presume that the pytz database is correct so what am I doing wrong? I'd be grateful of any suggestions.

"""
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))

Produces the following output:

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
Это было полезно?

Решение

You need to use the .localize() method to put a datetime in the correct timezone, otherwise a historical offset is chosen by mistake:

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))

See the pytz documenation:

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

With this change, the output becomes:

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

Note that the New York offsets were also incorrect.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top