Skip to content

Instantly share code, notes, and snippets.

@t00n t00n/
Created Dec 24, 2017

What would you like to do?
Small function to iterative over a time range
from datetime import datetime
from time import sleep
def trange(start=None, end=None, interval=1):
now =
if start is None:
start = now
start = start.timestamp()
if end is not None:
end = end.timestamp()
if start > now:
sleep(start - now)
now = start
i = 1
while end is None or now < end:
now =
target = start + i * interval
if target > now:
sleep(target - now)
now = target
i += 1
if __name__ == '__main__':
from datetime import timedelta
print(, "Starts now, end in 5 seconds, interval 1")
for t in trange( + timedelta(seconds=5)):
print(, "Starts in 5 seconds, ends in 10 seconds, interval 1")
for t in trange( + timedelta(seconds=5), + timedelta(seconds=10)):
print(, "Starts now, never ends, interval 5")
for t in trange(interval=5):
sleep(2) # as long as it's less than the interval it will work
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.