Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a timezone specific date in the past is daylight saving or not in python?

Is there a way I can check if a specific timezone is in daylight saving in a date I specified?

    test_dt = datetime(year=2015, month=2, day=1)
    pst = pytz.timezone('America/Los_Angeles')
    test_dt = pst.localize(test_dt) 

    # should return False
    is_day_light_saving(test_dt)        
like image 632
Kevin Avatar asked Jun 30 '15 18:06

Kevin


1 Answers

Just call the datetime.dst() method:

def is_summer_time(aware_dt):
    assert aware_dt.tzinfo is not None
    assert aware_dt.tzinfo.utcoffset(aware_dt) is not None
    return bool(aware_dt.dst())

Example:

#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz

naive = datetime(2015, 2, 1)
pacific = pytz.timezone('America/Los_Angeles')
aware = pacific.localize(naive, is_dst=None) 

print(is_summer_time(aware))

It is equivalent to:

bool(pytz.timezone('America/Los_Angeles').dst(datetime(2015, 2, 1), is_dst=None))
like image 197
jfs Avatar answered Sep 19 '22 01:09

jfs