我想在Python中推断日期是否是一年中由于DST(夏令时)而改变小时的实际日期。
与图书馆pytz
您可以本地化日期时间,并且实际的 DST 更改已正确完成。此外,还有一个方法dst()
图书馆的datetime
这使您可以推断实际日期是夏季还是冬季(example https://stackoverflow.com/questions/31146092/how-to-determine-if-a-timezone-specific-date-in-the-past-is-daylight-saving-or-n)。但是,我想推断 DST 更改的实际日期。
具体来说,我需要一个函数(例如is_dst_change(date, timezone)
) 接收日期并仅对于一年中确实存在小时变化的那些日子返回 True。例如:
import pytz
import datetime
def is_dst_change(day, timezone):
# Localize
loc_day = pytz.timezone(timezone).localize(day)
# Pseudocode: Infer if a date is the actual day in which the dst hour change is made
if loc_day is dst_change_day:
return True
else:
return False
# In the timezone 'Europe/Madrid', the days in which the DST change is made in 2021 are 28/03/2021 and 31/10/2021
is_dst_change(day=datetime.datetime(year=2021, month=3, day=28), timezone = 'Europe/Madrid') # This should return True
is_dst_change(day=datetime.datetime(year=2021, month=10, day=31), timezone = 'Europe/Madrid') # This should return True
is_dst_change(day=datetime.datetime(year=2021, month=2, day=1), timezone = 'Europe/Madrid') # This should return False
is_dst_change(day=datetime.datetime(year=2021, month=7, day=1), timezone = 'Europe/Madrid') # This should return False
因此,在上面的示例中,函数仅在 2021 年中使用is_dst_change(day, timezone='Europe/Madrid')
将返回True
分别是 2021 年 3 月 28 日和 2021 年 10 月 31 日。 2021 年剩下的日子里,它必须返回False
。有没有办法用Python来推断这一点?