Python:打印两个日期时间之间的所有小时数以节省时间 [英] Python: Printing all hours between two datetime accounting for daylight saving
问题描述
我想打印给定两个日期时间之间的所有小时数,以节省夏令时间.
I want to print all hours between given two datetime accounting for daylight savings.
这就是我的开始:
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
但是我该怎么做才能节省夏令时.如何跳或增加一小时的夏令时?
But what do I do for daylight time savings. How do I jump or add an hour for daylight savings ?
根据下面的建议,我编写了以下代码,它仍然显示了2016年的夏令时.
Based on suggestion below I wrote the following code and it still prints the daylight savings time for 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点.
Edit 2: Desired result: In march hour skips and at 2 AM it becomes 3 AM.
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 AM,它看起来应该像这样:
In Nov, an hour is added at 2 AM, so 2 AM repeats, it should look like:
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()方法来处理夏时制和其他时区转换,因此您应该修改您的代码以包含此内容
according to pytz when you want to do datetime arithimetics using local times you need to use normalize() method to handle daylight saving times and other timezone transitions hence your you should modify you code to include this
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上查看更多的此处
check pytz for more here
这篇关于Python:打印两个日期时间之间的所有小时数以节省时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!