PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Python DateTime » Python Difference Between Two Dates in Months and Years

Python Difference Between Two Dates in Months and Years

Updated on: December 1, 2026 | 1 Comment

In this article, you’ll learn how to find the number of years and months between two dates in Python. This is useful for calculating someone’s age, the length of a subscription or loan, or how long an employee has worked at a company.

This article is part of a series on Python Date and Time.

You’ll learn how to:

  • Get the years, months, and days between two dates with relativedelta.
  • Get the total number of months between two dates.
  • Count calendar months with the built-in datetime module, and understand how that differs from full months.
  • Calculate a person’s age in years.
  • Get an approximate difference as a decimal number of years or months.

Table of contents

  • How to calculate years and months between two dates
    • Example: Get Years, Months, and Days between two dates
    • Example: Get Only Months between two dates
    • What happens if the dates are in the wrong order?
  • Calculate Age in Years
  • Difference between two dates in months using datetime module
  • Calculate months between two datetime objects
  • Get the Difference as a Decimal Number of Years or Months
  • Months Between Dates in pandas
  • Summary

Also, see the difference between two dates in days in Python.

How to calculate years and months between two dates

Months and years don’t have a fixed length (a month has 28 to 31 days, and a year has 365 or 366), so you can’t simply divide a number of days. The dateutil package solves this with its relativedelta class, which describes the gap between two dates in years, months, days, and smaller units, following the calendar. The steps below show how to use it.

  1. Install and import dateutil

    dateutil is a third-party package that extends Python’s datetime module. Install it with pip install python-dateutil (it’s already installed if you use pandas), then import the class with from dateutil.relativedelta import relativedelta.

  2. Convert date strings to datetime objects

    If your dates are strings, first convert each string to a datetime object with datetime.strptime(date_str, format). For example, the format %d/%m/%Y matches 14/8/2019.

  3. Create a relativedelta object

    Call relativedelta(end_date, start_date). Put the later date first. The result describes the interval between the two dates.

  4. Read the years, months, and days

    Use the years, months, and days attributes of the relativedelta object.

  5. Get the total months

    The months attribute only holds the months left over after the full years (0 to 11). To get the total number of months, calculate delta.years * 12 + delta.months.

Example: Get Years, Months, and Days between two dates

Let’s find the difference between 14 August 2019 and 16 March 2022.

from datetime import datetime
from dateutil.relativedelta import relativedelta

d1 = '14/8/2019'
d2 = '16/3/2022'

# convert the strings to datetime objects
start_date = datetime.strptime(d1, "%d/%m/%Y")
end_date = datetime.strptime(d2, "%d/%m/%Y")

# get the relativedelta between the two dates
delta = relativedelta(end_date, start_date)
print(delta)
print(delta.years, 'years,', delta.months, 'months,', delta.days, 'days')Code language: Python (python)

Output:

relativedelta(years=+2, months=+7, days=+2)
2 years, 7 months, 2 days

From 14 August 2019, two full years take you to 14 August 2021. Seven more months take you to 14 March 2022, and two more days reach 16 March 2022.

Example: Get Only Months between two dates

Note: delta.months holds only the leftover months (0 to 11), not the total. To get the total number of months, multiply the years by 12 and add the months.

from datetime import datetime
from dateutil.relativedelta import relativedelta

start_date = datetime.strptime('14/8/2019', "%d/%m/%Y")
end_date = datetime.strptime('16/3/2022', "%d/%m/%Y")

delta = relativedelta(end_date, start_date)

total_months = delta.years * 12 + delta.months
print('Total months between two dates:', total_months)Code language: Python (python)

Output:

Total months between two dates: 31

What happens if the dates are in the wrong order?

If you pass the earlier date first, all values become negative. Use abs() if you only care about the size of the gap:

from datetime import date
from dateutil.relativedelta import relativedelta

delta = relativedelta(date(2019, 8, 14), date(2022, 3, 16))
print(delta.years, delta.months, delta.days)

total_months = abs(delta.years * 12 + delta.months)
print('Total months:', total_months)Code language: Python (python)

Output:

-2 -7 -2
Total months: 31

Calculate Age in Years

A person’s age is the number of full years since their birth date, which is exactly what relativedelta(...).years returns:

from datetime import date
from dateutil.relativedelta import relativedelta

def age(birth_date, on_date):
    return relativedelta(on_date, birth_date).years

birth = date(1994, 8, 24)
print(age(birth, date(2022, 8, 23)))   # one day before the birthday
print(age(birth, date(2022, 8, 24)))   # on the birthdayCode language: Python (python)

Output:

27
28

Use date.today() as the second argument to get someone’s current age. Without dateutil, you can compare the month and day yourself:

from datetime import date

def age(birth_date, on_date):
    years = on_date.year - birth_date.year
    # subtract one if the birthday hasn't happened yet this year
    if (on_date.month, on_date.day) < (birth_date.month, birth_date.day):
        years -= 1
    return years

print(age(date(1994, 8, 24), date(2022, 8, 23)))Code language: Python (python)

Output:

27

Difference between two dates in months using datetime module

If you don’t want to install dateutil, you can count calendar months with the built-in datetime module. This only looks at the year and month and ignores the day:

months = (end.year - start.year) * 12 + (end.month - start.month)Code language: Python (python)
from datetime import datetime

start = datetime.strptime('24/12/2021', "%d/%m/%Y")
end = datetime.strptime('26/3/2022', "%d/%m/%Y")

months = (end.year - start.year) * 12 + (end.month - start.month)
print('Difference between dates in months:', months)Code language: Python (python)

Output:

Difference between dates in months: 3

Calendar months vs full months: The formula above counts how many times the month changed, not how many full months passed. For example, from 30 January to 1 February is only 2 days, but the month changed once, so the formula returns 1. relativedelta counts full months and returns 0. Use the formula for questions like “how many monthly invoices were sent?”, and relativedelta when you need the real elapsed time.

from datetime import date
from dateutil.relativedelta import relativedelta

start = date(2022, 1, 30)
end = date(2022, 2, 1)

calendar_months = (end.year - start.year) * 12 + (end.month - start.month)
delta = relativedelta(end, start)

print('Calendar months:', calendar_months)
print('Full months:', delta.years * 12 + delta.months, '| days:', delta.days)Code language: Python (python)

Output:

Calendar months: 1
Full months: 0 | days: 2

Calculate months between two datetime objects

If you already have datetime objects, there’s nothing to convert. relativedelta also includes hours, minutes, and seconds in its result:

from datetime import datetime
from dateutil.relativedelta import relativedelta

start = datetime(2021, 10, 20, 9, 15, 32)
end = datetime(2022, 2, 20, 4, 25, 42)

delta = relativedelta(end, start)
print(delta)
print('Total months:', delta.years * 12 + delta.months)Code language: Python (python)

Output:

relativedelta(months=+3, days=+30, hours=+19, minutes=+10, seconds=+10)
Total months: 3

Because the end time (04:25) is earlier in the day than the start time (09:15), only 3 full months have passed (plus 30 days and some hours), not 4. The calendar-month formula would return 4.

Get the Difference as a Decimal Number of Years or Months

Sometimes an approximate value like “2.59 years” is enough, for example in charts or statistics. Divide the number of days by the average length of a year (365.25 days) or a month (about 30.44 days):

from datetime import date

start = date(2019, 8, 14)
end = date(2022, 3, 16)

days = (end - start).days
print('Days:', days)
print('Years (approx.):', round(days / 365.25, 2))
print('Months (approx.):', round(days / 30.44, 1))Code language: Python (python)

Output:

Days: 945
Years (approx.): 2.59
Months (approx.): 31.0

These are estimates. Use relativedelta when you need exact calendar results.

Months Between Dates in pandas

In pandas, convert the dates to monthly periods and subtract them. The result counts calendar months, like the datetime formula above:

import pandas as pd

df = pd.DataFrame({
    'start': pd.to_datetime(['2019-08-14', '2021-12-24']),
    'end': pd.to_datetime(['2022-03-16', '2022-03-26']),
})

df['months'] = (df['end'].dt.to_period('M') - df['start'].dt.to_period('M')).apply(lambda p: p.n)
print(df)Code language: Python (python)

Output:

       start        end  months
0 2019-08-14 2022-03-16      31
1 2021-12-24 2022-03-26       3

Summary

TaskUse
Years, months, and daysrelativedelta(end, start)
Total full monthsdelta.years * 12 + delta.months
Age in yearsrelativedelta(today, birth_date).years
Calendar months (no install)(end.year - start.year) * 12 + (end.month - start.month)
Approximate years(end - start).days / 365.25

Filed Under: Python, Python DateTime

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python DateTime

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
In: Python Python DateTime
TweetF  sharein  shareP  Pin

 Python DateTime

  • Python DateTime Guide
  • Python Get Current DateTime
  • Python DateTime Formatting
  • Python String to DateTime
  • Python Timestamp
  • Python Timedelta
  • Python TimeZones
  • List All TimeZones in Python

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com