Use Python to find out if a timezone currently in daylight savings time

Joey Mason picture Joey Mason · Nov 4, 2013 · Viewed 27k times · Source

We have a server that runs on GMT time. I need to write a Python script that determines if it's currently (at this very second) Daylight Savings Time (DST) in Los Angeles, CA. How can I accomplish this? I took a look at pytz and time, but I can't figure it out. I realize that I could create some logic such as comparing the current time in LA to GMT time, but it would be a lot cleaner if I could use a standard library instead.

Thanks

Edit: Here's some sample code of me setting up the timezone:

from pytz import timezone
import pytz
from datetime import datetime, timedelta

tz = timezone('America/Los_Angeles')
// Instantiate a datetime object using tz? 

Edit: Here's a snippet of code that will work. It's not elegant, which is why I'm asking if there's a library or something that is made for this. Maybe like a is_dst() function.

utc = timezone("UTC")
now = utc.localize(datetime.utcnow())
los_angeles_tz = timezone('America/Los_Angeles')
los_angeles_time = now.astimezone(los_angeles_tz)

delta = los_angeles_time.utcoffset()
dstDelta = timedelta(hours=-8)

is_dst = (delta == dstDelta)

Answer

Matt Johnson-Pint picture Matt Johnson-Pint · Nov 4, 2013
import pytz
from datetime import datetime, timedelta

def is_dst(zonename):
    tz = pytz.timezone(zonename)
    now = pytz.utc.localize(datetime.utcnow())
    return now.astimezone(tz).dst() != timedelta(0)

Usage:

>>> is_dst("America/Los_Angeles")
False

>>> is_dst("America/Sao_Paulo")
True