How do I find missing dates in a list of sorted dates?

前端 未结 8 1340
孤街浪徒
孤街浪徒 2021-02-04 04:15

In Python how do I find all the missing days in a sorted list of dates?

8条回答
  •  花落未央
    2021-02-04 04:48

    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)]
    

提交回复
热议问题