classification
Title: adding timedelta to datetime object is not timezone aware
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 2.7
process
Status: closed Resolution: third party
Dependencies: Superseder:
Assigned To: Nosy List: akira, belopolsky, gilsho, r.david.murray
Priority: normal Keywords:

Created on 2015-02-20 19:46 by gilsho, last changed 2015-03-02 23:53 by akira. This issue is now closed.

Messages (3)
msg236326 - (view) Author: Gil Shotan (gilsho) Date: 2015-02-20 19:46
I encountered a strange bug involving timezone aware datetime objects and timedelta objects.

The crux of the matter is that daylight savings time is considered a different timezone, and therefore the timezone of a datetime object is date dependent. However, adding a timedelta object to a datetime object seems to do the simple thing which is preserve the timezone object. The bug manifests itself whenever adding a timedelta object crosses a daylight savings time boundary.

The following code illustrates the problem. Note that the transition between PDT (Pacific daylight time) and PST (Pacific savings time) occurs on March 9th (ish)

>>> from datetime import datetime, timedelta
>>> import pytz
>>> tz = pytz.timezone('America/Los_Angeles')
>>> before = tz.localize(datetime(year=2015, month=3, day=8))
>>> before
datetime.datetime(2015, 3, 8, 0, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
>>> # notice PST timezone
>>> after_right = tz.localize(datetime(year=2015, month=3, day=10))
>>> after_right
datetime.datetime(2015, 3, 10, 0, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
>>> # notice PDT timezone
>>> after_wrong = before + timedelta(days=2)
>>> after_wrong
datetime.datetime(2015, 3, 10, 0, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
>>> # when calculated this way, the timezone remains at PST
msg236331 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2015-02-20 21:24
the tzinfo object is responsible for handling daylight savings time.  This looks like a bug in pytz.
msg237089 - (view) Author: Akira Li (akira) * Date: 2015-03-02 23:53
pytz explicitly documents this case (crossing DST boundary). There is 
tz.normalize() method.

> the tzinfo object is responsible for handling daylight savings time.  This looks like a bug in pytz.

Are any of tzinfo methods even called during `before + timedelta(days=2)`?

Also a DST transition is not the only reason the utc offset or tzname may 
change.
History
Date User Action Args
2015-03-02 23:53:20akirasetnosy: + akira
messages: + msg237089
2015-02-27 20:11:35belopolskysetstatus: open -> closed
resolution: third party
stage: resolved
2015-02-20 21:24:14r.david.murraysetnosy: + r.david.murray, belopolsky, - eric.araujo, dstufft
messages: + msg236331
components: + Library (Lib), - Distutils
2015-02-20 19:46:14gilshocreate