2

I think about how to iterate by data and time in following way:

2016-06-10,00:00
2016-06-10,01:30
2016-06-10,02:00
2016-06-10,02:30
....

Can somebody help me ?

Serenity
  • 35,289
  • 20
  • 120
  • 115
  • Have you tried to use Pandas? It's very easy to do this with Pandas. – Joe T. Boka Jun 08 '16 at 23:39
  • 1
    Not quite sure if you want to create a table like the one you showed, or loop every 30min for some other actions. If it is the later one, you can refer to: http://stackoverflow.com/questions/153584/how-to-iterate-over-a-timespan-after-days-hours-weeks-and-months-in-python – Helene Jun 08 '16 at 23:45

2 Answers2

4

Use timedelta to generate a range of datetime objects:

from datetime import timedelta, datetime

start_date = datetime(2016, 6, 9, 5, 0, 0)
for td in (start_date + timedelta(minutes=30*it) for it in xrange(10)):
    print td.strftime("%Y-%m-%d,%H:%M")

Output:

2016-06-09,05:00
2016-06-09,05:30
2016-06-09,06:00
2016-06-09,06:30
2016-06-09,07:00
2016-06-09,07:30
2016-06-09,08:00
2016-06-09,08:30
2016-06-09,09:00
2016-06-09,09:30
Serenity
  • 35,289
  • 20
  • 120
  • 115
  • To be python3 compatible you need a parenthesis in print. Also, you need to replace xrange() with range(). Thank you! – Daedalus Sep 30 '20 at 09:51
2
import datetime
from datetime import timedelta

format = "%Y-%m-%d,%H:%M"

start = datetime.datetime(2016, 6, 10, 0, 0)

minutes = 0

for i in range(6):
    print (start + timedelta(minutes=minutes)).strftime(format)
    minutes += 30

Output:

$ python timespan.py  
2016-06-10,00:00  
2016-06-10,00:30  
2016-06-10,01:00  
2016-06-10,01:30  
2016-06-10,02:00  
2016-06-10,02:30