Created
August 16, 2014 15:42
-
-
Save dpapathanasiou/09bd2885813038d7d3eb to your computer and use it in GitHub Desktop.
How to tell if Daylight Savings Time is in effect using Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
import pytz | |
def is_dst (): | |
"""Determine whether or not Daylight Savings Time (DST) | |
is currently in effect""" | |
x = datetime(datetime.now().year, 1, 1, 0, 0, 0, tzinfo=pytz.timezone('US/Eastern')) # Jan 1 of this year | |
y = datetime.now(pytz.timezone('US/Eastern')) | |
# if DST is in effect, their offsets will be different | |
return not (y.utcoffset() == x.utcoffset()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sorry @oqamar but you are mistaken and have dived into a classic Northern hemisphere bias trap. In the southern Hemisphere, this premise:
is erroneous as we have DST on Jan 1. Your test is also broken, (confirmation bias at play), because in 2020 in Sydney Oct 5 was in DST and Oct 4 was NOT:
https://www.timeanddate.com/time/change/australia/sydney?year=2020
Once you've localized a datetime in fact you can simply check it's .dst() method to see if it's zero.
Your script is easily fixed and made simpler as follows:
This passes the Sydney test ;-), producing: