Date difference in months

Python, Date · Oct 28, 2020

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

More like this

  • Date difference in days

    Calculates the day difference between two dates.

    Python, Date · Oct 28, 2020

  • Date range

    Creates a list of dates between start (inclusive) and end (not inclusive).

    Python, Date · Jan 7, 2021

  • Days ago

    Calculates the date of n days ago from today.

    Python, Date · Oct 28, 2020