我试图在两次之间循环,每隔15分钟从8:00到17:00
预期输出将是
之类的列表[8:00, 8:15, 8:30, 8:45, 9:00]
到目前为止我已经
了now = datetime(2013, 2, 9, 8, 00)
end = now + timedelta(hours=9)
但我无法弄清楚如何运行循环以返回我想要的列表。
感谢您的光临。
答案 0 :(得分:4)
你是说这个?
>>> 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
../..
答案 1 :(得分:3)
这有效:
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']
答案 2 :(得分:2)
l=[]
while now<end:
l.append(now)
now+=timedelta(minutes=15)
答案 3 :(得分:2)
如果您可以提前计算列表中元素的数量,可以使用:
输入:
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']
答案 4 :(得分:1)
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)
如果您需要更频繁地使用步进时间范围。
答案 5 :(得分:1)
我会认真地给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
您还可以提供一个停止时间,这对您的问题来说就是一个很好的例子。