Ign*_*aBo 5 python timezone datetime pytz
我想在Python中推断日期是否是一年中由于DST(夏令时)而改变小时的实际日期。
使用该库,pytz您可以本地化日期时间,并且正确完成实际的 DST 更改。dst()此外,库的方法datetime允许您推断实际日期是夏季还是冬季(示例)。但是,我想推断 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
Run Code Online (Sandbox Code Playgroud)
因此,在上面的示例中,该函数is_dst_change(day, timezone='Europe/Madrid')将返回2021 年的唯一日期True是 2021 年 3 月 28 日和 2021 年 10 月 31 日。2021年剩下的日子里,它必须回归False。有没有办法用Python来推断这一点?
您可以使用datetime.dst()(UTC 偏移量的更改不一定是 DST 转换):
from datetime import datetime, time, timedelta
from zoneinfo import ZoneInfo # Python 3.9+
def is_date_of_DSTtransition(dt: datetime, zone: str) -> bool:
"""
check if the date part of a datetime object falls on the date
of a DST transition.
"""
_d = datetime.combine(dt.date(), time.min).replace(tzinfo=ZoneInfo(zone))
return _d.dst() != (_d+timedelta(1)).dst()
Run Code Online (Sandbox Code Playgroud)
例如 tz欧洲/柏林:
for d in range(366):
if is_date_of_DSTtransition(datetime(2021, 1, 1) + timedelta(d), "Europe/Berlin"):
print((datetime(2021, 1, 1) + timedelta(d)).date())
# 2021-03-28
# 2021-10-31
Run Code Online (Sandbox Code Playgroud)
注意:我在这里使用zoneinfo而不是pytz; 对于遗留代码,有一个pytz 弃用垫片。无论如何,这是一个pytz版本(需要额外的normalize):
import pytz
def is_date_of_DSTtransition(dt: datetime, zone: str) -> bool:
_d = pytz.timezone(zone).localize(datetime.combine(dt.date(), time.min))
return _d.dst() != pytz.timezone(zone).normalize(_d+timedelta(1)).dst()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2038 次 |
| 最近记录: |