Split a list of dates into subsets of consecutive dates
More itertools has a function called consecutive_groups
that does this for you:
Or you can view the source code and copy it's approach:
from datetime import datetime
from itertools import groupby
from operator import itemgetter
def consecutive_groups(iterable, ordering=lambda x: x):
for k, g in groupby(enumerate(iterable), key=lambda x: x[0] - ordering(x[1])):
yield map(itemgetter(1), g)
for g in consecutive_groups(dates, lambda x: datetime.strptime(x, '%Y-%m-%d').toordinal()):
print(list(g))
['2020-01-01', '2020-01-02', '2020-01-03']
['2020-01-06', '2020-01-07', '2020-01-08']