Generate a time sequence in 7 second increments

How do you create the following sequence of lines 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. End around 03:30: +/-

I would come up with a solution that uses modular arithmetic (first 1200 to have hours, not 60 minutes, and the rest are seconds, and numbers must be converted to strings, and "one place" strings must be prefixed with "0" ") ...

Is there a smarter (pythonic) solution using some helper generators in the standard library or list comprehension?

+3


source to share


4 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

      



+7


source


Try this



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

      

+4


source


I think you are overcomplicating things by looking at generators and understanding the list. Python's 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)

      

+2


source


This creates a time for every 5 minutes between 9:00 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]:

      

0


source







All Articles