python 计算date之间的差值,并罗列出来区间的月份

from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
def month_diff(start_date, end_date):
    start_date = datetime.strptime(start_date, "%Y-%m")
    end_date = datetime.strptime(end_date, "%Y-%m")

    month_diff = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month)

    months = []
    for i in range(month_diff + 1):
        current_month = start_date + relativedelta(months=i)
        months.append(current_month)
    months.sort(reverse=False)
    return months

# 示例
old_start_month = "2022-01"
old_end_month = "2023-03"

oldresult = month_diff(old_start_month, old_end_month)


new_start_month = "2021-11"
new_end_month = "2023-05"

newresult = month_diff(new_start_month, new_end_month)


diff = list(set(oldresult)-set(newresult))
diff.sort(reverse=False)
print(diff)

你可能感兴趣的:(Python,python)