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

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

    A good way of getting this done in Python is as follows. You need not worry about efficiency unless you have dates from multiple years in your list and this code always needs to run as per user interaction and yield output immediately.

    1. Get missing dates from one list (sorted or not)

    Create a function that gives you all the dates from start_date to end_date. And use it.

    import datetime
    
    def get_dates(start_date, end_date):
        span_between_dates = range(end_date - start_date).days
        for index in span_between_dates + 1:
            # +1 is to make start and end dates inclusive.
            yield start_date + datetime.timedelta(index)
    
    my_date_list = ['2017-03-05', '2017-03_07', ...]
    # Edit my_date_list as per your requirement.
    start_date = min(my_date_list)
    end_date = max(my_date_list)
    for current_date in get_dates(start_date, end_date)
        if date not in my_date_list:
            print date
    
    1. Get missing or overlapping dates between two date ranges.

    get_dates function should be defined.

    my_other_date_list = []  # your other date range
    start_date = min(my_date_list)
    end_date = max(my_date_list)
    for current_date in get_dates(start_date, end_date)
        if (date in my_date_range) and (date in my_other_date_list):
            print ('overlapping dates between 2 lists:')
            print date
        elif (date in my_date_range) and (date not in my_other_date_list):
            print ('missing dates:')
            print date
    

提交回复
热议问题