我试图在两次之间循环,从8:00到17:00,每15分钟一次
预期输出将是类似的时间列表
[8:00, 8:15, 8:30, 8:45, 9:00]
到目前为止,我得到了
now = datetime(2013, 2, 9, 8, 00)
end = now + timedelta(hours=9)
但我不知道如何运行循环来返回我想要的列表。
谢谢你的光临。
你是这个意思吗?
>>> now = datetime(2013,2,9,8,0)
>>> end = now + timedelta(hours=9)
>>> while now <= end:
print 'doing something at', now
now += timedelta(minutes=15)
doing something at 2013-02-09 08:00:00
doing something at 2013-02-09 08:15:00
doing something at 2013-02-09 08:30:00
doing something at 2013-02-09 08:45:00
../..
这是有效的:
import datetime
now = datetime.datetime(2013, 2, 9, 8, 00)
end=now+datetime.timedelta(hours=9)
l=[]
while now<=end:
l.append(now)
now+=datetime.timedelta(minutes=15)
print [t.strftime("%H:%M") for t in l]
打印:
['08:00', '08:15', '08:30', '08:45', '09:00', '09:15', '09:30', '09:45', '10:00', '10:15', '10:30', '10:45', '11:00', '11:15', '11:30', '11:45', '12:00', '12:15', '12:30', '12:45', '13:00', '13:15', '13:30', '13:45', '14:00', '14:15', '14:30', '14:45', '15:00', '15:15', '15:30', '15:45', '16:00', '16:15', '16:30', '16:45', '17:00']
l=[]
while now<end:
l.append(now)
now+=timedelta(minutes=15)
如果你可以提前计算列表中的元素数量,你可以使用这个:
输入:
import datetime
now = datetime.datetime(2013, 2, 9, 8, 00)
print [(now + datetime.timedelta(minutes=15*n)).strftime('%H:%M') for n in range(37)]
输出:
['08:00', '08:15', '08:30', '08:45', '09:00', '09:15', '09:30', '09:45', '10:00', '10:15', '10:30', '10:45', '11:00', '11:15', '11:30', '11:45', '12:00', '12:15', '12:30', '12:45', '13:00', '13:15', '13:30', '13:45', '14:00', '14:15', '14:30', '14:45', '15:00', '15:15', '15:30', '15:45', '16:00', '16:15', '16:30', '16:45', '17:00']
import datetime as dt
def timerange (start, end, step):
while start < end:
yield start
start += step
for x in timerange (dt.datetime (2013, 2, 9, 8), dt.datetime (2013, 2, 9, 17), dt.timedelta (minutes = 15) ):
print (x)
以防您需要更频繁地分级时间范围。
我会认真地看Delorean一眼,这样做就像for循环一样简单。
>>> import delorean
>>> from delorean import stops
>>> for stop in stops(freq=delorean.MINUTELY, count=4, start=d1, interval=15):
... print stop.datetime
...
2012-05-06 00:00:00+00:00
2012-05-06 00:15:00+00:00
2012-05-06 00:30:00+00:00
2012-05-06 00:45:00+00:00
你也可以提供一个停止时间,这将是你的问题的一个很好的例子。