Question

So I currently have a line of code which looks like this:

        t1 = datetime(self.year, self.month, self.day, self.hour, self.minute, self.second)
        ...
        t2 = timedelta(days=dayNum, hours=time2.hour, minutes=time2.minute, seconds=time2.second)
        sumVal = t1 + t2

I would like for the result to take into account any DST affects that might occur (such as if I am at 11/4/2012 00:30 AM and add 3 hours, I would get 02:30 AM, due to a fall back for DST). I've looked at using pytz and python-dateutil, and neither of them seem to support this, or at least not support it without a separate file which contains all of the time zones. The kicker is that the times may not necessarily be in the same time zone as the current system, or even be in the past. I'm sure there is a simple way to do this (or I would expect so out of Python), but nothing seems to be what I need right now. Any ideas?

Was it helpful?

Solution

Perhaps pytz's normalize method is what you are looking for:

import datetime as dt
import pytz

tz=pytz.timezone('Europe/London')
t1 = dt.datetime(2012,10,28,0,30,0)
t1=tz.localize(t1)
t2 = dt.timedelta(hours=3)
sumVal = t1 + t2

sumVal remains in BST:

print(repr(sumVal))
# datetime.datetime(2012, 10, 28, 3, 30, tzinfo=<DstTzInfo 'Europe/London' BST+1:00:00 DST>)

After normalization, sumVal is in GMT:

sumVal = tz.normalize(sumVal)
print(repr(sumVal))
# datetime.datetime(2012, 10, 28, 2, 30, tzinfo=<DstTzInfo 'Europe/London' GMT0:00:00 STD>)

Note, for London, the DST transition occurs at 2012-10-28 02:00:00.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top