LHB LHB - 19 days ago 6
Python Question

Create list of interval times given start and stop time

Given string Start and Stop dates/times and number of intervals by which I want to count the time in between:

import datetime
from datetime import timedelta
Start = '16 Sep 2016 00:00:00'
Stop= '16 Sep 2016 06:00:00.00'
ScenLength = 21600 # in seconds (21600 for 6 hours; 18000 for 5 hours; 14400 for 4 hours)
stepsize = 10 # seconds
Intervals = ScenLength/stepsize


how do I create a list of those dates and times?

I am new to Python and don't have much so far:

TimeList=[]
TimeSpan = [datetime.datetime.strptime(Stop,'%d %b %Y %H:%M:%S')-datetime.datetime.strptime(Start,'%d %b %Y %H:%M:%S')]
for m in range(0, Intervals):
...
TimeList.append(...)


Thanks!

Answer

If I understood correctly, you want to find time stamps in a regular interval.

That can be done with the Python class datetime.timedelta:

import datetime

start = datetime.datetime.strptime('16 Sep 2016 00:00:00', '%d %b %Y %H:%M:%S')
stop = datetime.datetime.strptime('16 Sep 2016 06:00:00', '%d %b %Y %H:%M:%S')

stepsize = 10
delta = datetime.timedelta(seconds=stepsize)

times = []
while start < stop:
    times.append(start)
    start += delta

print( times )

edit: complete example