[New-bugs-announce] [issue23494] adding timedelta to datetime object is not timezone aware

Gil Shotan report at bugs.python.org
Fri Feb 20 20:46:14 CET 2015


New submission from Gil Shotan:

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

----------
components: Distutils
messages: 236326
nosy: dstufft, eric.araujo, gilsho
priority: normal
severity: normal
status: open
title: adding timedelta to datetime object is not timezone aware
type: behavior
versions: Python 2.7

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue23494>
_______________________________________


More information about the New-bugs-announce mailing list