将Python datetime拆分为小时对齐的块

将Python datetime拆分为小时对齐的块,python,datetime,split,Python,Datetime,Split,我有一个datetime.datetime实例,d和一个datetime.timedelta实例td,我试图编写一个函数,将(d,d+td)范围分解为[(d,x1),(x1,x2),…,(xn,d+td)],其中xn变量都与小时对齐 例如,如果 d = datetime.datetime(2012, 9, 8, 18, 53, 34) td = datetime.timedelta(hours=2, minutes=34, seconds=5) 我想要一份清单 [(datetime.datet

我有一个
datetime.datetime
实例,
d
和一个
datetime.timedelta
实例
td
,我试图编写一个函数,将
(d,d+td)
范围分解为
[(d,x1),(x1,x2),…,(xn,d+td)]
,其中
xn
变量都与小时对齐

例如,如果

d = datetime.datetime(2012, 9, 8, 18, 53, 34)
td = datetime.timedelta(hours=2, minutes=34, seconds=5)
我想要一份清单

[(datetime.datetime(..., 18, 53, 34), datetime.datetime(..., 19, 0, 0)),
 (datetime.datetime(..., 19, 0, 0), datetime.datetime(..., 20, 0, 0)),
 (datetime.datetime(..., 20, 0, 0), datetime.datetime(..., 21, 0, 0)),
 (datetime.datetime(..., 21, 0, 0), datetime.datetime(..., 21, 27, 39))]
有人能提出一个很好的、类似于蟒蛇的方法来实现这一点吗?

chunks=[]
chunks = []
end = d + td

current = d
# Set next_current to the next hour-aligned datetime
next_current = (d + datetime.timedelta(hours=1)).replace(minute=0, second=0)

# Grab the start block (that ends on an hour alignment)
# and then any full-hour blocks
while next_current < end:
    chunks.append( (current, next_current) )

    # Advance both current and next_current to the following hour-aligned spots
    current = next_current
    next_current += datetime.timedelta(hours=1)

# Grab any remainder as the last segment
chunks.append( (current, end) )
结束=d+td 电流=d #将next_current设置为下一小时对齐日期时间 next_current=(d+datetime.timedelta(小时=1)).replace(分钟=0,秒=0) #抓住起始块(在一小时对齐时结束) #然后是整小时的街区 当下一个_电流<结束时: chunks.append((当前,下一个\当前)) #将当前和下一个_电流提前到以下时间点 电流=下一个\u电流 next_current+=datetime.timedelta(小时=1) #抓取任何余数作为最后一段 chunks.append((当前,结束))

这里的主要假设是,初始指定的timedelta不是负值。如果您这样做,您将得到一个单块列表
[(x,y)]
其中
y

使用,您可以使用:

屈服

2012-09-08 18:53:34
2012-09-08 19:00:00
2012-09-08 20:00:00
2012-09-08 21:00:00
2012-09-08 21:27:39
2012-09-08 18:53:34
2012-09-08 19:00:00
2012-09-08 20:00:00
2012-09-08 21:00:00
2012-09-08 21:27:39