Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate time sequence with step 7 seconds

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?

like image 907
xralf Avatar asked Mar 16 '12 11:03

xralf


1 Answers

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
like image 144
AdamKG Avatar answered Nov 02 '22 23:11

AdamKG