Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytz.astimezone not accounting for daylight savings?

Tags:

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!

like image 517
dholstius Avatar asked Sep 18 '13 01:09

dholstius


People also ask

Does pytz account for daylight savings?

Timedelta and DSTpytz will help you to tell if an date is under DST influence by checking dst() method.

How does Python handle daylight Savings?

You should use datetime. datetime. utcnow(). astimezone(tz) -- This gets the time in UTC and then offsets it from UTC according to whatever rules apply in the timezone tz.

What is the function to offset the date for daylight saving?

IsDaylightSavingTime(DateTimeOffset) Indicates whether a specified date and time falls in the range of daylight saving time for the time zone of the current TimeZoneInfo object.

How do you check is daylight saving is on in Python?

daylight() Function. Time. daylight() function which returns a non zero integer value when Daylight Saving Time (DST) is defined, else it returns 0.


1 Answers

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>)
like image 191
Mark Ransom Avatar answered Oct 06 '22 23:10

Mark Ransom