Search code examples
datetimepython-3.xpytz

Is this intended behavior or a bug in datetime timedelta?


from datetime import datetime timedelta
import pytz

ppt = pytz.timezone('US/Pacific')
first = ppt.localize(datetime(2013, 3, 10, 0, 0, 0))
first+=timedelta(hours=2)
first

returns datetime.datetime(2013, 3, 10, 2, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)

It should return datetime.datetime(2013, 3, 10, 3, 0, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)

You can workaround this, apparent, bug by doing astimezone(ppt) after adding the hours.

So, is this a bug? Am I doing it wrong? Or is it intended to have code refresh after adding time?


Solution

  • You need to call normalize() using the timezone object again when doing datetime arithmetic:

    >>> first
    datetime.datetime(2013, 3, 10, 2, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)
    >>> ppt.normalize(first)
    datetime.datetime(2013, 3, 10, 3, 0, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)
    

    As noted in the docs:

    In addition, if you perform date arithmetic on local times that cross DST boundaries, the result may be in an incorrect timezone. A normalize() method is provided to correct this.