我想在 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
因此,在上面的示例中,函式is_dst_change(day, timezone='Europe/Madrid')將回傳的 2021 年僅有的幾天True是 28/03/2021 和 31/10/2021。在 2021 年的剩余日子里,它必須回傳False。有沒有辦法用 Python 推斷出這一點?
uj5u.com熱心網友回復:
如果今天的 UTC 偏移量與明天的不同,那么今天是 DST 更改。
def is_dst_change(day: datetime.datetime, timezone):
# Override time to midnight
day = day.replace(hour=0, minute=0, second=0, microsecond=0)
tz = pytz.timezone(timezone)
return(tz.utcoffset(day datetime.timedelta(days=1)) !=
tz.utcoffset(day))
“今天”在此代碼中定義為午夜至午夜。
uj5u.com熱心網友回復:
您可以使用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()
例如對于 tz Europe/Berlin:
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
注意:我在這里使用zoneinfo而不是pytz; 對于遺留代碼,有一個pytz deprecation shim。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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/313688.html
