8

我试图在两次之间循环,从 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)

但我不知道如何运行循环来返回我想要的列表。

感谢您的关注。

4

6 回答 6

6

你是这个意思?

>>> 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
../..
于 2013-02-09T01:18:42.953 回答
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']
于 2013-02-09T01:29:56.203 回答
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']
于 2013-02-09T02:45:20.720 回答
2
l=[]

while now<end:
    l.append(now)
    now+=timedelta(minutes=15)
于 2013-02-09T01:18:54.263 回答
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

您还可以提供一个停止时间,这将是您问题的一个很好的例子。

于 2013-02-21T06:11:55.463 回答
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)

如果您需要更频繁地步进时间范围。

于 2013-02-09T03:13:42.503 回答