Skip to content

Instantly share code, notes, and snippets.

@felipe-prenholato
Created January 7, 2015 12:17
Show Gist options
  • Select an option

  • Save felipe-prenholato/66b1574ec72b9b4de37c to your computer and use it in GitHub Desktop.

Select an option

Save felipe-prenholato/66b1574ec72b9b4de37c to your computer and use it in GitHub Desktop.
step date range, generate slot list
def step_date_range(start, end, **step):
"""
Returns a range
:param start: datetime
:param end: datetime
:param step: keywords used in timedelta
:return: generator of date ranges
>>> list(step_date_range(datetime(2014, 12, 22, 0, 0),
... datetime(2014, 12, 22, 2, 50),
... minutes=30))
[datetime.datetime(2014, 12, 22, 0, 0), datetime.datetime(2014, 12, 22, 0, 30), \
datetime.datetime(2014, 12, 22, 1, 0), datetime.datetime(2014, 12, 22, 1, 30), \
datetime.datetime(2014, 12, 22, 2, 0), datetime.datetime(2014, 12, 22, 2, 30)]
"""
current = start
while current <= end:
yield current
current = current + timedelta(**step)
def generate_slot_list(start, end, step):
"""
Return a list of slots base on start time, end time and step.
:param start: tuple with (hour, minute) that list should start
:param end: tuple with (hour, minute) that list should stop
:param step: int from 1 to 59 indicating how minutes will be used as step
:return: list of slots like ['00:00 - 00:30', '00:30 - 01:00', '01:00 - 01:30', ...]
>>> list(generate_slot_list((0, 0), (2, 45), 30))
['00:00 - 00:30', '00:30 - 01:00', '01:00 - 01:30', '01:30 - 02:00', '02:00 - 02:30']
"""
assert 0 < step < 60, "step need to be between 1 and 59."
today = datetime.today()
date_range = step_date_range(today.replace(hour=start[0], minute=start[1]),
today.replace(hour=end[0], minute=end[1]),
minutes=step)
date_start = date_range.next()
for date_end in date_range:
yield '{:02d}:{:02d} - {:02d}:{:02d}'.format(date_start.hour, date_start.minute,
date_end.hour, date_end.minute)
date_start = date_end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment