Python:在两个日期时间之间的所有时间打印夏令时

时间:2016-05-20 14:23:53

标签: python datetime

我想在给定的两个日期时间会计之间打印所有小时以节省夏令时。

这就是我的开始:

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

1 个答案:

答案 0 :(得分:2)

根据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