python 计算两个日期相差多少个月
python 计算两个日期相差多少个月

python 计算两个日期相差多少个月
• 发表于 9个月前
• 阅读 23
• 收藏 0
• 评论 0

哦，对了，别跟我说 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}")``````

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

废话不多少，献上自己写的代码：

该代码返回，（月,小数月）

``````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}")``````

×