python 计算两个日期相差多少个月实例代码

近期,由于业务需要计算两个日期之前相差多少个月。我在网上找了很久,结果发现万能的python,居然没有一个模块计算两个日期的月数,像Java、C#之类的高级语言,都会有(date1-date2).months的现成方法,觉得不可思议。说句实在的,一直觉得python 的日期处理模块真心不好用。

哦,对了,别跟我说 datetime, calendar, dateutil 这些模块,因为我都试过了,都没用。有个竟然算出来还有错。datetime.timedelta只能计算出日时分秒。对年月却不支持。网上一搜,一大堆的。

dateutil.rrule这个例子是我好不容易找到的,请看我的测试结果:

import datetime

from dateutil import rrule

d1 = datetime.date(2016, 2, 29)
d2 = datetime.date(2019, 3, 31)

months = rrule.rrule(rrule.MONTHLY, dtstart=d1, until=d2).count()

print(f"months={months}")

python 计算两个日期相差多少个月实例代码

看到这样的结果,我只能呵呵了。

废话不多少,献上自己写的代码:

该代码返回,(月,小数月)

import datetime

import calendar as c



d1 = datetime.date(2016, 2, 29)

d2 = datetime.date(2019, 3, 31)



def calmonths(startdate, enddate):

# 计算两个日期相隔月差

samemonthdate = None

try:

samemonthdate = datetime.date(enddate.year, enddate.month,

startdate.day)

except Exception as e:

print(e)

samemonthdate = datetime.date(enddate.year, enddate.month,

c.monthrange(enddate.year,

enddate.month)[1])


holdmonths = 0

decimalmonth = 0.0

if samemonthdate > enddate:

premanthdate = None

try:

premanthdate = datetime.date(enddate.year, enddate.month - 1,

startdate.day)

except Exception as e:

print(e)

premanthdate = datetime.date(enddate.year, enddate.month - 1,

c.monthrange(

enddate.year,

enddate.month - 1)[1])

currmonthdays = (samemonthdate - premanthdate).days

holdmonths = (premanthdate.year - startdate.year

) * 12 + premanthdate.month - startdate.month

decimalmonth = (enddate - premanthdate).days / currmonthdays


elif samemonthdate < enddate:

nextmonthdate = None

try:

nextmonthdate = datetime.date(enddate.year, enddate.month + 1,

startdate.day)

except Exception as e:

nextmonthdate = datetime.date(enddate.year, enddate.month + 1,

c.monthrange(

enddate.year,

enddate.month + 1)[1])

currmonthdays = (nextmonthdate - samemonthdate).days

holdmonths = (samemonthdate.year - startdate.year

) * 12 + samemonthdate.month - startdate.month

decimalmonth = (enddate - samemonthdate).days / currmonthdays


else:

holdmonths = (enddate.year - startdate.year

) * 12 + enddate.month - startdate.month


return holdmonths, decimalmonth


months = calmonths(d1, d2)


print(f"months={months}")

python 计算两个日期相差多少个月实例代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持安科网。

相关推荐