6

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)        
Kevin
  • 301
  • 5
  • 13

2 Answers2

8

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))
jfs
  • 346,887
  • 152
  • 868
  • 1,518
-1

In my experience, timezone data is more easily dealt with timezone-sensitive pandas.Timestamp() than datetime. I am pretty sure the timezone-sensitivity infers daylight savings time from the date itself. It is trivial to convert datetime to pandas.timestamp() by first converting it to a numpy.datetime64.

Timestamp(numpy.datetime64('2012-05-01T01:00:00.000000'))

http://wesmckinney.com/blog/easy-high-performance-time-zone-handling-in-pandas-0-8-0/

python pandas TimeStamps to local time string with daylight saving

Converting between datetime, Timestamp and datetime64

Also you can try looking at the pandas source code and figuring out how it deduced the tz information. https://github.com/pydata/pandas/blob/master/pandas/src/datetime/np_datetime.c

Community
  • 1
  • 1