python 计算两个日期之间的月数差额

用python 计算两个日期之间的月数
一个多月认为是2个月
结果:

beginTime="2022-03-31"
endTime="2022-05-31" #输出2

beginTime="2022-03-31"
endTime="2022-05-30" #输出2

beginTime="2022-03-31"
endTime="2022-06-01" #输出3

代码:

from  datetime import datetime,date,timedelta
import time 


def month_delta(start_date, end_date):
    """
    返回 end_date  - start_date  的差值
        :param start_date:
        :param end_date:
        :return:  month_delta   int
    """
    flag = True
    if start_date > end_date:
        start_date, end_date = end_date, start_date
        flag = False
    year_diff = end_date.year - start_date.year
    day_diff = end_date.day - start_date.day
    end_month = year_diff * 12 + end_date.month
    if(day_diff > 0):
        end_month+=1
    delta = end_month - start_date.month
    return -delta if flag is False else delta


if __name__ == '__main__':
   # start = date(2017, 12, 31)
   # end = date(2018, 7, 2)
    beginTime="2022-03-31"
    endTime="2022-05-31"

    fmt='%Y-%m-%d'
    time1=time.strptime(beginTime,fmt)
    time2=time.strptime(endTime,fmt)
    year_begin,month_begin,day_begin=time1[:3]
    year_end,month_end,day_end=time2[:3]

    start = date(year_begin,month_begin,day_begin) 
    end = date(year_end,month_end,day_end)


    print(month_delta(start, end))
    #print(month_delta(end, start))

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