How would you generate the following sequence of strings in Python?
00:00:00
00:00:07
00:00:14
00:00:21
...
00:00:49
00:00:56
00:01:03
The step is 7 seconds. The end is about 03:30:+/-
I would come with solution that uses modular arithmetic (first 1200 to have hours, than 60 to have minutes and the remainder are seconds and the numbers should be converted to strings and "one-place" strings should be prefixed by "0").
Is there some smarter (pythonic) solution with using some helper generators in standard library or list comprehension?
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
Try this one
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
I think you're over complicating things by looking at generators and list comprehension. The Python datetime module will do this easily.
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)
This generates times for every 5 minutes between 9:00AM and 2.00PM==14:00.
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]: