Skip to content

Instantly share code, notes, and snippets.

@nguyent
Created September 27, 2016 22:39
Show Gist options
  • Select an option

  • Save nguyent/115b5ed2964e3a56a8ab011448fe707f to your computer and use it in GitHub Desktop.

Select an option

Save nguyent/115b5ed2964e3a56a8ab011448fe707f to your computer and use it in GitHub Desktop.
given a list of dates, create a list of lists containing contiguous ranges Raw
from datetime import timedelta
from datetime import datetime
def toDate(s):
return datetime.strptime(s, '%Y-%m-%d')
def consecutive(d1, d2):
return toDate(d1) + timedelta(days=1) == toDate(d2)
def findRangesRecursive(dates, acc=[], candidate=[]):
if not dates:
return acc + [candidate]
else:
current_day = dates[0]
if consecutive(candidate[-1], current_day):
candidate.append(current_day)
else:
acc.append(candidate)
candidate = [current_day]
return findRangesRecursive(dates[1:], acc, candidate)
def findRanges(dates):
return findRangesRecursive(dates[1:], acc=[], candidate=dates[0:1])
# we could be stricter and require dates be a list of datetime objects
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment