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

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

    USING A FOR LOOP

    The imports you'll need:

    import datetime
    from datetime import date, timedelta
    

    Let's say you have a sorted list called dates with several missing dates in it.

    First select the first and last date:

    start_date = dates[0]
    end_date = dates[len(dates)-1]
    

    Than count the number of days between these two dates:

    numdays = (end_date - start_date).days
    

    Than create a new list with all dates between start_date and end_date:

    all_dates = []
    for x in range (0, (numdays+1)):
    all_dates.append(start_date + datetime.timedelta(days = x))
    

    Than check with dates are in all_dates but not in dates by using a for loop with range and adding these dates to dates_missing:

    dates_missing = []
    
    for i in range (0, len(all_dates)):
       if (all_dates[i] not in dates):
           dates_missing.append(all_dates[i])
       else:
           pass
    

    Now you'll have a list called dates_missing with all the missing dates.

提交回复
热议问题