mark
mark

Reputation: 62836

Python: Strange behavior of datetime.astimezone with respect to US/Pacific and America/Los_Angeles time zones?

Please, observe:

C:\dev\poc\SDR>python
Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from pytz import timezone
>>> from datetime import datetime
>>> tz1=timezone('America/Los_Angeles')
>>> tz2=timezone('US/Pacific')
>>> ts1=datetime(2011,8,1,tzinfo=tz1)
>>> ts2=datetime(2011,8,1,tzinfo=tz2)
>>> ts1
datetime.datetime(2011, 8, 1, 0, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
>>> ts2
datetime.datetime(2011, 8, 1, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)
>>> ts1.astimezone(tz1)
datetime.datetime(2011, 8, 1, 0, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
>>> ts2.astimezone(tz2)
datetime.datetime(2011, 8, 1, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)
>>> ts1.astimezone(tz2)
datetime.datetime(2011, 8, 1, 1, 0, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)
>>> ts2.astimezone(tz1)
datetime.datetime(2011, 8, 1, 1, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
>>>

Here is what I do not understand. US/Pacific (tz1) and America/Los_Angeles (tz2) are supposed to denote the same time zone, aren't they? Then how come that datetime.astimezone called to move from one zone to another changes the hour?

Thanks.

Upvotes: 4

Views: 1063

Answers (1)

Amber
Amber

Reputation: 527063

Daylight Savings Time. Notice that the last two entries are listing PDT-1.

astimezone takes into account DST, but only if it actually goes through its full logic.

The first two astimezone calls in your example don't go through the full logic, because they short-circuit (since the timezone they're converting "to" already matches the one they're converting "from").

(You might wonder why the initial datetimes aren't using PDT already. This is because the datetime constructor doesn't take into account daylight savings time, even if you pass it a timezone - it just sets the timezone blindly.)

Upvotes: 4

Related Questions