如何在python中确定过去的时区特定日期是否为夏令时?

时间:2015-06-30 18:47:49

标签: python datetime time timezone

有没有办法可以检查特定时区是否在我指定的日期进行夏令时?

    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)        

2 个答案:

答案 0 :(得分:7)

只需致电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())

示例:

#!/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))

相当于:

bool(pytz.timezone('America/Los_Angeles').dst(datetime(2015, 2, 1), is_dst=None))

答案 1 :(得分:-1)

根据我的经验,时区数据更容易处理时区敏感的pandas.Timestamp()而不是datetime。我非常确定时区灵敏度可以从日期本身推断夏令时。通过首先将datetime转换为numpy.datetime64,将datetime转换为pandas.timestamp()是微不足道的。

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

您也可以尝试查看pandas源代码并弄清楚它是如何推断出tz信息的。 https://github.com/pydata/pandas/blob/master/pandas/src/datetime/np_datetime.c