30秒学会 Python 片段 · 2022年12月9日

30秒学会 Python 片段 – Date difference in months

Calculates the month difference between two dates.

  • Subtract start from end and use datetime.timedelta.days to get the day difference.
  • Divide by 30 and use math.ceil() to get the difference in months (rounded up).

代码实现

from math import ceil

def months_diff(start, end):
  return ceil((end - start).days / 30)

使用样例

from datetime import date

months_diff(date(2020, 10, 28), date(2020, 11, 25)) # 1

翻译自:https://www.30secondsofcode.org/python/s/months-diff