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

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

    >>> from datetime import datetime, timedelta
    >>> date_list = [datetime(2010, 2, 23),datetime(2010, 2, 24),datetime(2010, 2, 25),datetime(2010, 2, 26),datetime(2010, 3, 1),datetime(2010, 3, 2)]
    >>> 
    >>> date_set=set(date_list)         # for faster membership tests than list
    >>> one_day = timedelta(days=1)
    >>> 
    >>> test_date = date_list[0]
    >>> missing_dates=[]
    >>> while test_date < date_list[-1]:
    ...     if test_date not in date_set:
    ...         missing_dates.append(test_date)
    ...     test_date += one_day
    ... 
    >>> print missing_dates
    [datetime.datetime(2010, 2, 27, 0, 0), datetime.datetime(2010, 2, 28, 0, 0)]
    

    This also works for datetime.date objects, but the OP says the list is datetime.datetime objects

提交回复
热议问题