In Python how do I find all the missing days in a sorted list of dates?
Put the dates in a set
and then iterate from the first date to the last using datetime.timedelta()
, checking for containment in the set each time.
Using a list comprehension
>>> from datetime import date, timedelta
>>> d = [date(2010, 2, 23),date(2010, 2, 24),date(2010, 2, 25),date(2010, 2, 26),date(2010, 3, 1),date(2010, 3, 2)]
>>> date_set=set(d)
>>> missing = [x for x in (d[0]+timedelta(x) for x in range((d[-1]-d[0]).days)) if x not in date_set]
>>> missing
[datetime.date(2010, 2, 27), datetime.date(2010, 2, 28)]