16

I'm looking for a method of determining when DST starts or ends for a given timezone in a Python script I'm working on.

I know pytz can convert the UTC dates I'm working into localtime, and will take DST into account, however for this particular application I need to know the point of the changeover.

Any suggestions?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Smingos
  • 280
  • 1
  • 3
  • 9
  • 2
    For which year? DST change points have changed in the history in some timezones. – eumiro Sep 29 '11 at 08:46
  • 1
    Well, ideally I'd like to be able to do it for an arbitrary year. I know this sort of info is available in the Olsen database, but accessing it is another matter. – Smingos Sep 29 '11 at 08:48

1 Answers1

26

You could have a look to the _utc_transition_times memberof the timezone you're using.

>>> from pytz import timezone
>>> tz = timezone("Europe/Paris")
>>> print tz._utc_transition_times

[datetime.datetime(1, 1, 1, 0, 0), datetime.datetime(1911, 3, 10, 23, 51, 39), datetime.datetime(1916, 6, 14, 23, 0), datetime.datetime(1916, 10, 1, 23, 0), date
....
 datetime.datetime(2037, 3, 29, 1, 0), datetime.datetime(2037, 10, 25, 1, 0)]

It will give you the list of the DST change dates (start and end of DST).

According to the code of tzinfo.py

class DstTzInfo(BaseTzInfo):
    '''A timezone that has a variable offset from UTC

    The offset might change if daylight savings time comes into effect,
    or at a point in history when the region decides to change their
    timezone definition.
    '''
    # Overridden in subclass
    _utc_transition_times = None # Sorted list of DST transition times in UTC
    _transition_info = None # [(utcoffset, dstoffset, tzname)] corresponding
                            # to _utc_transition_times entries

So if you mix the _utc_transition_times with _transition_info you will grab all your needed informations, date, time and offset to apply ;)

Cédric Julien
  • 78,516
  • 15
  • 127
  • 132
  • This looks very well. Didn't know about that attribute. – eumiro Sep 29 '11 at 08:53
  • I'll give that a try as soon as I'm home, thanks. Do those dates mark the start or end of DST? – Smingos Sep 29 '11 at 08:59
  • For Europe/Paris the beginning of DST is mostly in March, its end in September/October. But since these dates are the __changes__, you can count on the odd/even position in this list. – eumiro Sep 29 '11 at 09:05
  • @Smingos : the dates are the start and the end of DST for each year, I updated my answer with the informations I found in the pytz code. – Cédric Julien Sep 29 '11 at 09:11
  • That sounds perfect. As I said, I'll give it a try this evening. Thanks again! – Smingos Sep 29 '11 at 09:20