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

前端 未结 8 1268
孤街浪徒
孤街浪徒 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:39

    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.

    0 讨论(0)
  • 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)]
    
    0 讨论(0)
提交回复
热议问题