Skip to content

Instantly share code, notes, and snippets.

@efloehr
Created February 5, 2015 01:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save efloehr/3e1dd639f3c5c1b064b7 to your computer and use it in GitHub Desktop.
Save efloehr/3e1dd639f3c5c1b064b7 to your computer and use it in GitHub Desktop.
from datetime import timedelta, date
from copy import copy
# Takes either string in form "2014-01-01" or date, and return days with day_step in between
# If start is after end and day_step is not specified, it will change it to -1 automatically, otherwise
# day_step defaults to 1 day
def day_generator(start_day=None, end_day=None, day_step=None):
if start_day is None:
start_day = date.today() - timedelta(day=1)
elif type(start_day) == str:
year, month, day = [ int(x) for x in start_day.split('-') ]
start_day = date(year, month, day)
if end_day is None:
end_day = start_day
elif type(end_day) == str:
year, month, day = [ int(x) for x in end_day.split('-') ]
end_day = date(year, month, day)
current_day = copy(start_day)
if day_step is None:
if end_day < start_day:
day_step = -1
else:
day_step = 1
range_start = min(start_day, end_day)
range_end = max(start_day, end_day)
while current_day >= range_start and current_day <= range_end:
yield current_day
current_day += timedelta(days=day_step)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment