我想打印给定的两个日期时间之间的所有小时,以考虑夏令时。

这是我开始的:

from datetime import date, timedelta as td, datetime

d1 = datetime(2008, 8, 15, 1, 1, 0)
d2 = datetime(2008, 9, 15, 1, 12, 4)

while(d1<d2):
    d1 = d1 + td(hours=1)
    print d1

但是我该怎么做才能节省夏令时。如何跳跃或增加一个小时的夏令时?

编辑:
根据下面的建议,我编写了以下代码,它仍然打印 2016 年的夏令时。
import pytz
from datetime import date, timedelta as td, datetime
eastern = pytz.timezone('US/Eastern')

d1 = eastern.localize(datetime(2016, 3, 11, 21, 0, 0))
d2 = eastern.localize(datetime(2016, 3, 12, 5, 0, 0))

d3 = eastern.localize(datetime(2016, 11, 4, 21, 0, 0))
d4 = eastern.localize(datetime(2016, 11, 5, 5, 0, 0))

while(d1<d2):
    print d1
    d1 = d1 + td(hours=1)

while(d3<d4):
    print d3
    d3 = d3 + td(hours=1)

输出:
2016-03-11 21:00:00-05:00
2016-03-11 22:00:00-05:00
2016-03-11 23:00:00-05:00
2016-03-12 00:00:00-05:00
2016-03-12 01:00:00-05:00
2016-03-12 02:00:00-05:00
2016-03-12 03:00:00-05:00
2016-03-12 04:00:00-05:00

2016-11-04 21:00:00-04:00
2016-11-04 22:00:00-04:00
2016-11-04 23:00:00-04:00
2016-11-05 00:00:00-04:00
2016-11-05 01:00:00-04:00
2016-11-05 02:00:00-04:00
2016-11-05 03:00:00-04:00
2016-11-05 04:00:00-04:00

编辑2:
想要的结果:
在三月,时间跳过,在凌晨 2 点变为凌晨 3 点。
2016-03-11 23:00:00-05:00
2016-03-12 00:00:00-05:00
2016-03-12 01:00:00-05:00
2016-03-12 03:00:00-05:00

在 11 月,在凌晨 2 点添加一个小时,因此重复凌晨 2 点,它应该如下所示:
2016-11-04 23:00:00-04:00
2016-11-05 00:00:00-04:00
2016-11-05 01:00:00-04:00
2016-11-05 02:00:00-04:00
2016-11-05 02:00:00-04:00
2016-11-05 03:00:00-04:00

最佳答案

根据pytz,当您想使用本地时间进行日期时间算术时,您需要使用 normalize() 方法来处理夏令时和其他时区转换,因此您应该修改代码以包含此内容

import pytz
from datetime import date, timedelta as td, datetime
eastern = pytz.timezone('US/Eastern')

d1 = eastern.localize(datetime(2016, 3, 11, 21, 0, 0))
d2 = eastern.localize(datetime(2016, 3, 12, 5, 0, 0))

d3 = eastern.localize(datetime(2016, 11, 4, 21, 0, 0))
d4 = eastern.localize(datetime(2016, 11, 5, 5, 0, 0))

while(d1<d2):
    print d1
    d1 = eastern.normalize(d1 + td(hours=1))

while(d3<d4):
    print d3
    d3 = eastern.normalize(d3 + td(hours=1))

检查 pytz 以获取更多 here

关于Python:打印两个日期时间之间的所有小时数以进行夏令时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37349258/

10-12 18:10