用于日期计算的带有 relativedelta 的奇怪算术
Strange arithmetic with relativedelta for date calculations
我正在使用 relativedelta 来计算两个日期之间的差异。但是,似乎无法识别日期时间对象的年份部分。如果日期是同一年月,则获得的计算将有意义。
# lease dates
start = json_obj['lease'][0]['start']
end = json_obj['lease'][0]['end']
print(end, start)
2026-10-31 2020-10-07
startdt = datetime.strptime(start, '%Y-%m-%d')
print(startdt)
2020-10-07 00:00:00
enddt = datetime.strptime(end, '%Y-%m-%d')
print(enddt)
2026-10-31 00:00:00
# Total months
calc = relativedelta.relativedelta(enddt, startdt)
calc.days
24
calc.months
0
没有月份,所以calc.months
return 0
:
# Total months
calc = relativedelta.relativedelta(enddt, startdt)
print (calc)
relativedelta(years=+6, days=+24)
如果需要所有月份乘以 12
并添加月份:
print (calc.months + calc.years * 12)
72
我正在使用 relativedelta 来计算两个日期之间的差异。但是,似乎无法识别日期时间对象的年份部分。如果日期是同一年月,则获得的计算将有意义。
# lease dates
start = json_obj['lease'][0]['start']
end = json_obj['lease'][0]['end']
print(end, start)
2026-10-31 2020-10-07
startdt = datetime.strptime(start, '%Y-%m-%d')
print(startdt)
2020-10-07 00:00:00
enddt = datetime.strptime(end, '%Y-%m-%d')
print(enddt)
2026-10-31 00:00:00
# Total months
calc = relativedelta.relativedelta(enddt, startdt)
calc.days
24
calc.months
0
没有月份,所以calc.months
return 0
:
# Total months
calc = relativedelta.relativedelta(enddt, startdt)
print (calc)
relativedelta(years=+6, days=+24)
如果需要所有月份乘以 12
并添加月份:
print (calc.months + calc.years * 12)
72