使用步骤7秒生成时间序列

时间:2012-03-16 11:07:48

标签: python generator sequence list-comprehension

如何在Python中生成以下字符串序列?

00:00:00
00:00:07
00:00:14
00:00:21
...
00:00:49
00:00:56
00:01:03

这一步是7秒。结束时间约为03:30:+/-

我会使用模块化算法的解决方案(首先1200小时,小于60分钟,余数是秒,数字应转换为字符串,“单位”字符串应以“0”为前缀“)。

是否有一些更聪明的(pythonic)解决方案在标准库或列表理解中使用了一些辅助生成器?

4 个答案:

答案 0 :(得分:7)

def yield_times():
    from datetime import date, time, datetime, timedelta
    start = datetime.combine(date.today(), time(0, 0))
    yield start.strftime("%H:%M:%S")
    while True:
        start += timedelta(seconds=7)
        yield start.strftime("%H:%M:%S")

>>> gen = yield_times()
>>> for ii in range(5):
...     print gen.next()
... 
00:00:00
00:00:07
00:00:14
00:00:21
00:00:28

答案 1 :(得分:4)

试试这个

from datetime import datetime, timedelta

now = datetime(2000, 1, 1, 0, 0, 0)
last = datetime(2000, 1, 1, 3, 30, 0)
delta = timedelta(seconds=7)

times = []
while now < last:
    times.append(now.strftime('%H:%M:%S'))
    now += delta

答案 2 :(得分:2)

我认为你通过查看生成器和列表理解来使事情复杂化。 Python datetime module可以轻松完成此任务。

from datetime import datetime, timedelta

t = datetime(2012, 1, 1, 0, 0, 0)

while t < datetime(2012, 1, 1, 3, 30, 0):
    print t.time()

    t = t + timedelta(seconds=7)

答案 3 :(得分:0)

这会在上午9:00到下午2:00 == 14:00之间每5分钟生成一次。

In [1]: from datetime import datetime

In [2]: [str(datetime(2012, 1, 1, hr, min, 0).time()) for hr in range(9,14) for min in range(0,60,5)]
Out[2]:
['09:00:00',
 '09:05:00',
 '09:10:00',
 '09:15:00',
 '09:20:00',
 '09:25:00',
 '09:30:00',
 '09:35:00',
 '09:40:00',
 '09:45:00',
 '09:50:00',
 '09:55:00',
 '10:00:00',
 '10:05:00',
 '10:10:00',
 '10:15:00',
 '10:20:00',
 '10:25:00',
 '10:30:00',
 '10:35:00',
 '10:40:00',
 '10:45:00',
 '10:50:00',
 '10:55:00',
 '11:00:00',
 '11:05:00',
 '11:10:00',
 '11:15:00',
 '11:20:00',
 '11:25:00',
 '11:30:00',
 '11:35:00',
 '11:40:00',
 '11:45:00',
 '11:50:00',
 '11:55:00',
 '12:00:00',
 '12:05:00',
 '12:10:00',
 '12:15:00',
 '12:20:00',
 '12:25:00',
 '12:30:00',
 '12:35:00',
 '12:40:00',
 '12:45:00',
 '12:50:00',
 '12:55:00',
 '13:00:00',
 '13:05:00',
 '13:10:00',
 '13:15:00',
 '13:20:00',
 '13:25:00',
 '13:30:00',
 '13:35:00',
 '13:40:00',
 '13:45:00',
 '13:50:00',
 '13:55:00']

In [3]: