[英]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. 我想在给定的两个日期时间之间打印所有时间来计算夏令时。
This is what I have started at: 这是我开始的:
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 ?
如何跳跃或增加一小时的夏令时?
Edit: Based on suggestion below I wrote the following code and it still prints the daylight savings time for 2016. 编辑:根据下面的建议,我编写了以下代码,它仍然打印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)
Output: 输出:
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
Edit 2: Desired result: In march hour skips and at 2 AM it becomes 3 AM. 编辑2:所需结果:在3月份跳过,在凌晨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
In Nov, an hour is added at 2 AM, so 2 AM repeats, it should look like: 在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
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 根据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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.