Python DST and timezone detection after adding

So, I have a line of code that 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 the result to take into account any DST consequences that may occur (for example, if I am on 11/4/2012 00:30 and add 3 hours, I get 02:30 in the morning, due to the back for DST). I looked at using pytz and python-dateutil, and none of them seem to support this, or at least not support it without a separate file that contains all time zones. The kicker is that time may not necessarily be in the same time zone as the current system, or even be in the past. I am sure there is an easy way to do this (or I would expect this from Python), but right now there is nothing that I need. Any ideas?

+7
source share
1 answer

Perhaps the pytz 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 stays 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 .

+5
source

All Articles