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

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

    Sort the list of dates and iterate over it, remembering the previous entry. If the difference between the previous and current entry is more than one day, you have missing days.

    Here's one way to implement it:

    from datetime import date, timedelta
    from itertools import tee, izip
    
    def pairwise(iterable):
        "s -> (s0,s1), (s1,s2), (s2, s3), ..."
        a, b = tee(iterable)
        b.next()
        return izip(a, b)
    
    def missing_dates(dates):
        for prev, curr in pairwise(sorted(dates)):
            i = prev
            while i + timedelta(1) < curr:
                i += timedelta(1)
                yield i
    
    dates = [ date(2010, 1, 8),
              date(2010, 1, 2),
              date(2010, 1, 5),
              date(2010, 1, 1),
              date(2010, 1, 7) ]
    
    for missing in missing_dates(dates):
        print missing
    

    Output:

    2010-01-03
    2010-01-04
    2010-01-06
    

    Performance is O(n*log(n)) where n is the number of days in the span when the input is unsorted. As your list is already sorted, it will run in O(n).

提交回复
热议问题