gpt4 book ai didi

python - DST 更改前后的日期和时区代码

转载 作者:行者123 更新时间:2023-11-28 18:41:01 25 4
gpt4 key购买 nike

我正在测试如何根据夏令时的变化计算和显示日期(使用时区代码)。

在英国,2014 年 3 月 30 日凌晨 1 点,我们进入 DST,从 GMT 转到 BST。时间从 2014-03-30 00:59:59 GMT 跳到 2014-03-30 02:00:00 BST

我在使用以下代码复制它时遇到了一个奇怪的问题:

import pytz
from datetime import datetime, time, timedelta

def is_dst(d, tz):
assert d.tzinfo is None # we want a naive datetime to localize
return tz.localize(d).dst() != timedelta(0)

start_datetime = datetime(2014, 03, 30, 0, 0, 0)
tz = pytz.timezone('Europe/London')

# Increment using timedelta
print 'This doesn\'t work:'
d = start_datetime
for i in range(5):
print str(d) + ' ' + tz.tzname(d, is_dst=is_dst(d, tz))
d += timedelta(minutes=30) # Add 30 minutes

# Increment by adding seconds to epoch
print 'This works:'
epoch = datetime.utcfromtimestamp(0)
timestamp = (start_datetime - epoch).total_seconds()
for i in range(5):
d = datetime.fromtimestamp(timestamp)
print str(d) + ' ' + tz.tzname(d, is_dst=is_dst(d, tz))
timestamp += 30 * 60 # Add 30 minutes

输出是:

This doesn't work:
2014-03-30 00:00:00 GMT
2014-03-30 00:30:00 GMT
2014-03-30 01:00:00 GMT <- invalid time
2014-03-30 01:30:00 GMT <- invalid time
2014-03-30 02:00:00 BST
This works:
2014-03-30 00:00:00 GMT
2014-03-30 00:30:00 GMT
2014-03-30 02:00:00 BST
2014-03-30 02:30:00 BST
2014-03-30 03:00:00 BST

我在输出中标记了无效时间。挂钟上没有这些时间,2014 年 3 月 30 日没有凌晨 1 点或凌晨 1:30,所以我不确定为什么会显示它。

相同的过程但以稍微不同的方式完成会产生正确的结果。这是为什么?

最佳答案

这是 @Matt Johnson's answer根据 my comments 修改:

from datetime import datetime, timedelta
import pytz

tz = pytz.timezone('Europe/London')
#NOTE: is_dst=None asserts that the local time exists and unambiguous
start_datetime = tz.localize(datetime(2014, 03, 30, 0, 0, 0), is_dst=None)

# increment using timedelta
print 'This works:'
d = start_datetime.astimezone(pytz.utc) # use UTC to do arithmetic
for _ in range(5):
local = d.astimezone(tz) # use local timezone for display only
print("\t{:%F %T %Z%z}".format(local))
d += timedelta(minutes=30) # works in UTC

# increment by adding seconds to epoch
print 'This works too:'
epoch = datetime(1970, 1, 1, tzinfo=pytz.utc)
timestamp = (start_datetime - epoch).total_seconds()
for i in range(5):
local = datetime.fromtimestamp(timestamp, tz)
print("\t{:%F %T %Z%z}".format(local))
timestamp += 30 * 60 # add 30 minutes

关于python - DST 更改前后的日期和时区代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26021782/

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