首页 > 编程 > Python > 正文

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

2020-01-04 17:13:04
字体:
来源:转载
供稿:网友

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

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

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

import datetimefrom dateutil import rruled1 = 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 datetimeimport calendar as cd1 = datetime.date(2016, 2, 29)d2 = datetime.date(2019, 3, 31)def calmonths(startdate, enddate):# 计算两个日期相隔月差samemonthdate = Nonetry: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 = 0decimalmonth = 0.0if samemonthdate > enddate:premanthdate = Nonetry: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).daysholdmonths = (premanthdate.year - startdate.year) * 12 + premanthdate.month - startdate.monthdecimalmonth = (enddate - premanthdate).days / currmonthdayselif samemonthdate < enddate:nextmonthdate = Nonetry: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).daysholdmonths = (samemonthdate.year - startdate.year) * 12 + samemonthdate.month - startdate.monthdecimalmonth = (enddate - samemonthdate).days / currmonthdayselse:holdmonths = (enddate.year - startdate.year) * 12 + enddate.month - startdate.monthreturn holdmonths, decimalmonthmonths = calmonths(d1, d2)print(f"months={months}")

python,日期相差天数,相差月份,日期差多少月

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表