给定一系列日期区间,求这段日期区间的交集

def CountDays(start_time, end_time, time_interval_list):
    from datetime import datetime, timedelta
    
    time_a = []
    for start, end in time_interval_list:
        if end is None:
            end = end_time
        time_a.append([datetime.strptime(start, '%Y%m%d'),
                       datetime.strptime(end, '%Y%m%d')])

    start_time = datetime.strptime(start_time, '%Y%m%d')
    end_time = datetime.strptime(end_time, '%Y%m%d')

    corrected_time_a = []
    for s, e in time_a:
        if e < start_time or s > end_time:
            continue
        elif s <= start_time <= e:
            s = start_time
        elif s <= end_time <= e:
            e = end_time
        corrected_time_a.append([s, e])
    if len(corrected_time_a) == 0:
        return (end_time - start_time).days + 1, 0

    b = []
    for begin, end in sorted(corrected_time_a):
        if b and b[-1][1] >= begin - timedelta(days=1):
            b[-1][1] = max(b[-1][1], end)
        else:
            b.append([begin, end])

    occupied_days = sum((j-i).days + 1 for i, j in b)
    free_days = (end_time - start_time).days + 1 - occupied_days
    return free_days, occupied_days


CountDays('20221020', '20240531',
          [['20221005', '20221221'],
           ['20231204', '20231231'],
           ['20210402', '20210502'],
           ['20240402', '20240402']])

CountDays('20211020', '20220531',
          [['20221005', '20221221'],
           ['20231204', '20231231'],
           ['20210402', '20210502'],
           ['20240402', '20240402'],
           ['20221005', None]])

求日期区间的并集的代码思路参考自Union of multiple ranges

posted on 2024-09-15 17:07  纵横二剑  阅读(6)  评论(0编辑  收藏  举报