gpt4 book ai didi

python - 有没有办法在 Python 中推断日期是否是 DST(夏令时)更改发生的实际日期?

转载 作者:行者123 更新时间:2023-12-04 14:02:42 24 4
gpt4 key购买 nike

我想在 Python 中推断日期是否是一年中由于 DST(夏令时)而改变小时的实际日期。

使用库 pytz,您可以本地化日期时间并正确完成实际的 DST 更改。此外,库 datetime 的方法 dst() 允许您推断实际日期是夏令时还是冬令时 (example)。但是,我想推断 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') 将返回 True 的 2021 年仅有的几天是 28/03/2021 和 31/10/2021。对于 2021 年的剩余时间,它必须返回 False。有没有办法用 Python 推断这一点?

最佳答案

如果今天的 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))

“今天”在此代码中定义为午夜至午夜。

关于python - 有没有办法在 Python 中推断日期是否是 DST(夏令时)更改发生的实际日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69483502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com