2012-09-08 37 views
4

我有一個datetime.datetime實例,ddatetime.timedelta實例td並在嘗試寫會分崩離析範圍(d, d+td)[(d,x1),(x1,x2),...,(xn,d+td)]xn變量都對齊到小時的功能。拆分一個Python日期時間爲一小時的對齊的短語

例如,如果

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))] 

任何人都可以提出一個很好的,Python化,是指實現這個的?

回答

6

使用dateutil,你可以使用rrule生成列表:

import dateutil.rrule as rrule 
import datetime 

def hours_aligned(start, end, inc = True): 
    if inc: yield start 
    rule = rrule.rrule(rrule.HOURLY, byminute = 0, bysecond = 0, dtstart=start) 
    for x in rule.between(start, end, inc = False): 
     yield x 
    if inc: yield end 

d = datetime.datetime(2012, 9, 8, 18, 53, 34) 
td = datetime.timedelta(hours=2, minutes=34, seconds=5) 

for x in hours_aligned(d,d+td): 
    print(x) 

產量

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 
+0

感謝修正,@FreddieWitherden。 – unutbu

1
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)) 

這裏的主要假設是你最初的指定timedelta不爲負。你會得到一個單塊列表[(x,y)]其中y < x如果你這樣做。

相關問題