Python:在两个日期时间之间打印所有小时来计算夏令时

我想在给定的两个日期时间之间打印所有时间来计算夏令时.

这是我开始的:

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:
期望的结果:
在三月小时跳过,凌晨两点它变成凌晨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,当你想使用本地时间做datetime算术时,你需要使用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

点赞