Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

python - pytz.astimezone not accounting for daylight savings?

On 2013 Jun 1 I expect the "PST8PDT" timezone to behave like GMT+7, as it is daylight savings in that timezone. However, it behaves like GMT+8:

>>> import pytz, datetime
>>> Pacific = pytz.timezone("PST8PDT")
>>> datetime.datetime(2013, 6, 1, 12, tzinfo=Pacific).astimezone(pytz.utc)
datetime.datetime(2013, 6, 1, 20, 0, tzinfo=<UTC>)

In contrast, on 2013 Jan 1 it behaves (correctly) like GMT+8:

>>> datetime.datetime(2013, 1, 1, 12, tzinfo=Pacific).astimezone(pytz.utc)
datetime.datetime(2013, 1, 1, 20, 0, tzinfo=<UTC>)

What am I doing wrong? Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't assign the timezone in the datetime constructor, because it doesn't give the timezone object a chance to adjust for daylight savings - the date isn't accessible to it. This causes even more problems for certain parts of the world, where the name and offset of the timezone have changed over the years.

From the pytz documentation:

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

Use the localize method with a naive datetime instead.

>>> Pacific.localize(datetime.datetime(2013, 6, 1, 12)).astimezone(pytz.utc)
datetime.datetime(2013, 6, 1, 19, 0, tzinfo=<UTC>)
>>> Pacific.localize(datetime.datetime(2013, 1, 1, 12)).astimezone(pytz.utc)
datetime.datetime(2013, 1, 1, 20, 0, tzinfo=<UTC>)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...