How to Get the Number of Months Between Two Dates in Python

The billing lead at an Austin coworking space asked me for the number of months between two dates in Python, one count per member contract, so she could bill $249.50 for every full month.

Subtracting two dates gives a timedelta in days, and dividing by 30 in Python drifts by a month on real contracts because months run 28 to 31 days.

Quick answer: for calendar months, use (end.year - start.year) * 12 + (end.month - start.month). For full months that respect the day, use relativedelta:

from dateutil.relativedelta import relativedelta
gap = relativedelta(end, start)
months = gap.years * 12 + gap.months

In this tutorial, I’ll show how to get the number of months between two dates in Python with plain datetime, dateutil and pandas. Every Command Prompt screenshot is a real Python 3.12.5 run.

The Contract Dates We’ll Measure

Every example below uses four member contracts saved as contracts.py:

# Member contracts at an Austin coworking space
from datetime import date

CONTRACTS = [
    ("Emily Carter", date(2025, 3, 10), date(2026, 11, 26)),
    ("James Ortiz", date(2026, 1, 31), date(2026, 2, 28)),
    ("Olivia Reed", date(2025, 6, 15), date(2026, 6, 14)),
    ("Noah Brooks", date(2026, 9, 30), date(2026, 10, 1)),
]

James ends on a month end and Noah’s contract lasts a single day, so you’ll see each method treat them differently. Got the dates as text? Convert the string to a date in Python first.

Count Calendar Months Between Two Dates in Python

The simplest Python answer ignores the day of the month and counts month boundaries. It needs no imports:

from contracts import CONTRACTS


def calendar_months(start, end):
    return (end.year - start.year) * 12 + (end.month - start.month)


for name, start, end in CONTRACTS:
    print(f"{name:<13} {start} -> {end}: {calendar_months(start, end):>2}")

Output:

Emily Carter  2025-03-10 -> 2026-11-26: 20
James Ortiz   2026-01-31 -> 2026-02-28:  1
Olivia Reed   2025-06-15 -> 2026-06-14: 12
Noah Brooks   2026-09-30 -> 2026-10-01:  1
Number of months between two dates in Python: Command Prompt output of the calendar month formula for four contracts
Calendar months: 20, 1, 12 and 1. Noah’s one-day contract still counts as a month.

That gives 20, 1, 12 and 1. Noah gets a full month for September 30 to October 1, which is wrong for billing.

This matches SQL Server’s DATEDIFF(month, ...), which also counts boundaries crossed. If you only need the day count, see calculating the days between two dates in Python.

Get Full Months Between Two Dates with relativedelta

relativedelta from python-dateutil (2.9.0.post0 here; pip install python-dateutil) splits the gap into years, months and days. Same four contracts, now billed:

from dateutil.relativedelta import relativedelta
from contracts import CONTRACTS

FEE = 249.50                     # monthly membership in USD

for name, start, end in CONTRACTS:
    gap = relativedelta(end, start)
    months = gap.years * 12 + gap.months
    print(f"{name:<13} {months:>2} months {gap.days:>2} days"
          f"  billed ${months * FEE:,.2f}")

Output:

Emily Carter  20 months 16 days  billed $4,990.00
James Ortiz    1 months  0 days  billed $249.50
Olivia Reed   11 months 30 days  billed $2,744.50
Noah Brooks    0 months  1 days  billed $0.00
Command Prompt output of Python relativedelta showing full months, leftover days and USD billing per contract
Full months: 20, 1, 11 and 0, with the leftover days and the billed amount.

Emily is billed $4,990.00 for 20 full months, and Noah pays $0.00. Olivia drops to 11 months because June 14 falls one day short of her start day.

How does this code work? relativedelta(end, start) walks from the start date by whole months first, then counts the remaining days. .months alone stays between 0 and 11, so add years * 12.

James is the surprise: January 31 to February 28 is exactly one month, because relativedelta clamps a month-end start to the last day of a shorter month. It’s the closest match to Excel’s DATEDIF with “m”.

Why Doesn’t Python timedelta Have Months?

A timedelta stores days, seconds and microseconds only, since a month has no fixed length. Asking for months=1 fails, and day division only approximates:

from datetime import timedelta
from contracts import CONTRACTS

try:
    timedelta(months=1)
except TypeError as err:
    print("TypeError:", err)

for name, start, end in CONTRACTS:
    days = (end - start).days
    print(f"{name:<13} {days:>3} days  /30.4375 = "
          f"{days / 30.4375:5.2f}  //30 = {days // 30}")

Output:

TypeError: 'months' is an invalid keyword argument for __new__()
Emily Carter  626 days  /30.4375 = 20.57  //30 = 20
James Ortiz    28 days  /30.4375 =  0.92  //30 = 0
Olivia Reed   364 days  /30.4375 = 11.96  //30 = 12
Noah Brooks     1 days  /30.4375 =  0.03  //30 = 0
Command Prompt output of Python timedelta(months=1) raising TypeError and days divided by 30 for each contract
timedelta rejects months, and dividing days gives 0.92 for a full month and 12 for an 11-month contract.

James’s full month comes out as 0.92, and // 30 gives Olivia 12. In Python, use day division only for rough reporting, like an average tenure in months. timedelta is still the right tool for subtracting days from a date in Python.

Find the Months Between Two Dates in pandas

For a CSV or Excel export, do the whole column at once. Here are the contracts in a pandas 3.0.6 DataFrame:

import numpy as np
import pandas as pd
from contracts import CONTRACTS

df = pd.DataFrame(CONTRACTS, columns=["member", "start", "end"])
df[["start", "end"]] = df[["start", "end"]].apply(pd.to_datetime)

gap = df["end"].dt.to_period("M") - df["start"].dt.to_period("M")
df["months"] = gap.apply(lambda offset: offset.n)
print(df)

try:
    (df["end"] - df["start"]) / np.timedelta64(1, "M")
except ValueError as err:
    print("ValueError:", str(err)[:60])

Output:

         member      start        end  months
0  Emily Carter 2025-03-10 2026-11-26      20
1   James Ortiz 2026-01-31 2026-02-28       1
2   Olivia Reed 2025-06-15 2026-06-14      12
3   Noah Brooks 2026-09-30 2026-10-01       1
ValueError: Unit M is not supported. Only unambiguous timedelta values d
Command Prompt output of a pandas DataFrame with a months column from to_period and the timedelta64 M ValueError
The months column holds 20, 1, 12 and 1; dividing by np.timedelta64(1, “M”) raises ValueError.

to_period("M") turns each date into its month, so subtracting gives calendar months, the same 20, 1, 12 and 1 as the first formula. offset.n reads the count from each result.

The old np.timedelta64(1, "M") trick now raises ValueError, so don’t copy it from older answers. If your columns are strings, convert the pandas column to datetime first.

List Each Month Between Two Dates in Python

Sometimes your Python script needs the months themselves, say one invoice row per month. pd.period_range() gives every month the range touches:

import pandas as pd

months = pd.period_range("2026-01-15", "2026-06-14", freq="M")
print(len(months), months.strftime("%b %Y").tolist())

Output:

6 ['Jan 2026', 'Feb 2026', 'Mar 2026', 'Apr 2026', 'May 2026', 'Jun 2026']

That returns 6 months, January through June 2026, including both partial months. Need the last day of each one for a due date? Here’s how to get the last day of a month in Python.

Month Count Mistakes That Skew Your Python Results

Python month counts usually go wrong in three places I’ve hit on client data:

  • Reversed dates: relativedelta returns negative months, so check that start comes first.
  • Datetimes with times: 9 AM to 8 AM the same day a month later is one day short; use .date() first.
  • Month names: “March” isn’t a date; convert the month name to a number first.

Keep reading with these date posts:

Questions About Months Between Dates in Python

How do I get the number of months between two dates in Python?

Use the year-and-month formula for calendar months, or relativedelta for full months.

How do I find the difference between two dates in months in Python?

Call relativedelta(end, start) and add years * 12 + months; leftover days are in .days.

Can timedelta store months in Python?

No. timedelta(months=1) raises TypeError because months vary in length.

How do I count months between two date columns in pandas?

Subtract dt.to_period("M") values and read .n from each result.

Does relativedelta count a partial month?

No. It returns whole months plus leftover days, so round up yourself if you bill partial months.

Where is timedelta documented?