Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine when DST starts or ends in a specific location in Python? [duplicate]

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?

like image 385
Smingos Avatar asked Sep 29 '11 08:09

Smingos


People also ask

How do you know if its daylight savings time in python?

You can use time. localtime and look at the tm_isdst flag in the return value. Using time. localtime() , you can ask the same question for any arbitrary time to see whether DST would be (or was) in effect for your current time zone.

How do you know if daylight savings is on or off?

Most of the United States begins Daylight Saving Time at 2:00 a.m. on the second Sunday in March and reverts to standard time on the first Sunday in November. In the U.S., each time zone switches at a different time. In the European Union, Summer Time begins and ends at 1:00 a.m. Universal Time (Greenwich Mean Time).

What is the function to offset the date for daylight saving Python?

utcoffset(dt) - This method is used to get the DST offset in the zones where DST is in effect. If the DST is not in effect, it will return only timedelta(0). The DTC information is already part of the UTC offset.


1 Answers

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 ;)

like image 63
Cédric Julien Avatar answered Sep 25 '22 14:09

Cédric Julien