Every year some day in march, our government steals a whole hour from us, holds it ransom over the summer and gives it back only in october – only to steal it again next year. I’m talking about daylight savings time of course, which we switched to just this night. And while it is annoying and useless enough on its own, it means a world of pain in Python.
Problem
As it turned out this DST-business caused some unwanted behavior in a little project I’m working on. I had to figure out how to reliable compute the offset that is added to the correct time during DST on any given date. This is what I came up with.
Solution
First you will need the Pytz package. It’s not part of the standard library for one reason or another, but it comes preinstalled in a lot of Linux distributions. easy_install will happily install it for you if it isn’t, even on Windows.
To get the DST offset, there are really only three and a half steps to take:
tz = pytz.timezone('Europe/Berlin')
date = datetime.datetime(2012,3,25,12)
dstoffset = tz.localize(date).dst()
This will give you a nice timedelta(0,3600) object which tells you that on the 25th of march 2012 at noon, the DST offsets the correct time by 3600 seconds. Likewise on the 24th, the offset is 0 seconds.
Explanation
First you need to create a tzone object for the desired timezone. For me, this is Europe/Berlin.
tz = pytz.timezone('Europe/Berlin')
Then you create a datetime object for the given date and time you want to compute the DST for.
date = datetime.datetime(2012,3,25,12)
The trick is in the localize function of your tzone object. The datetime object you created does not contain any timezone information at all. localize assumes that the timezone information is simply missing and magically creates a new datetime object with the same date and time and correct timezone. Luckily for us, this includes DST. We then just need to call the dst method, which gives you the offset as a timedelta object.
dstoffset = tz.localize(date).dst()