我正在尝试使用relativedelta查找两个日期之间的月份差异。我可以找到年和天的差异,但是当我筛选月份时,我得到0。有什么建议吗?
from dateutil import relativedelta as rd
import datetime as date
dateformat = '%Y/%m/%d'
startDate = date.strptime('2017/07/01',dateformat).date()
endDate = date.strptime('2019/10/29',dateformat).date()
date_diff = rd.relativedelta(endDate,startDate)
print(date_diff.days)
答案 0 :(得分:1)
这是解决方案:
from datetime import datetime
def diff_month(d1, d2):
return (d1.year - d2.year) * 12 + d1.month - d2.month
assert diff_month(datetime(2010,10,1), datetime(2010,9,1)) == 1
assert diff_month(datetime(2010,10,1), datetime(2009,10,1)) == 12
答案 1 :(得分:0)
end-start将产生timedelta对象,其天数属性将达到所需的天差
>>> from datetime import date
>>> start = date(2017,7,1)
>>> end = date(2017,11,11)
>>> (end-start).days
133
答案 2 :(得分:0)
relativedelta
将差异显示为年,月和日。如果这正是您要查找的内容,则不会显示 netmonth 。如果两个日期恰好在不同年份的同一个月,则months
属性将为零。
如果要显示总月份,则可以编写一个小函数,通过增加年值来实现。
from datetime import datetime
from dateutil.relativedelta import relativedelta
def month_delta(start_date, end_date):
delta = relativedelta(end_date, start_date)
# >>> relativedelta(years=+2, months=+3, days=+28)
return 12 * delta.years + delta.months
d1 = datetime(2017, 7, 1)
d2 = datetime(2019, 10, 29)
total_months = month_delta(d1, d2)
print(total_months)
# >>> 27