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

In this tutorial, I will explain how to get the number of months between two dates in Python. As a Python developer, I faced this issue while working on a project for a client in New York, where I had to calculate the number of months between various start and end dates for a series of financial transactions. Let’s learn more about this topic in detail.

Prerequisites

Before we start, make sure you have done Python installation on your system. You can download it from the official Python website. Additionally, we will use the dateutil library, which is not included in the standard library but can be easily installed via pip:

pip install python-dateutil

Read How to Calculate the Number of Days Between Two Dates in Python?

Methods to Get Number of Months Between Two Dates in Python

Python provides several ways to get number of months between two dates in Python, Let us see some methods.

1. Use the dateutil Library in Python

The dateutil library provides powerful extensions to the standard datetime module, making it easier to manipulate dates and times. One of its handy features is the relativedelta function, which we will use to calculate the difference in months between the two dates.

Example

Let’s consider two dates: January 15, 2023, and November 13, 2024. We want to calculate the number of months between these two dates.

from datetime import datetime
from dateutil.relativedelta import relativedelta

# Define the start and end dates
start_date = datetime(2023, 1, 15)
end_date = datetime(2024, 11, 13)

# Calculate the difference using relativedelta
difference = relativedelta(end_date, start_date)

# Calculate the total number of months
total_months = difference.years * 12 + difference.months

print(f"The number of months between {start_date.date()} and {end_date.date()} is {total_months} months.")

Output:

The number of months between 2023-01-15 and 2024-11-13 is 21 months.

I have executed the above example and added the screenshot below.

Number of Months Between Two Dates in Python

In this example, relativedelta calculates the difference in terms of years, months, and days. We then convert the years to months and add the remaining months to get the total number of months.

Check out How to Get a Week Number from Date in Python?

2. Use Pandas for DataFrame Operations in Python

If you are working with data stored in a DataFrame, you can use the pandas library to calculate the number of months between dates in different rows. Here’s how you can do it:

Example

First, make sure you have pandas installed:

pip install pandas

Now, let’s create a DataFrame and calculate the number of months between two date columns.

import pandas as pd
from dateutil.relativedelta import relativedelta

# Create a sample DataFrame
data = {
    'start_date': ['2023-01-15', '2022-03-10', '2021-07-25'],
    'end_date': ['2024-11-13', '2023-05-15', '2022-09-30']
}

df = pd.DataFrame(data)

# Convert the date columns to datetime
df['start_date'] = pd.to_datetime(df['start_date'])
df['end_date'] = pd.to_datetime(df['end_date'])

# Function to calculate the number of months between two dates
def calculate_months(row):
    difference = relativedelta(row['end_date'], row['start_date'])
    total_months = difference.years * 12 + difference.months
    return total_months

# Apply the function to the DataFrame
df['total_months'] = df.apply(calculate_months, axis=1)

print(df)

Output:

  start_date   end_date  total_months
0 2023-01-15 2024-11-13            21
1 2022-03-10 2023-05-15            14
2 2021-07-25 2022-09-30            14

I have executed the above example and added the screenshot below.

Get Number of Months Between Two Dates in Python

In this example, we used pandas to handle date columns in a DataFrame and applied a custom function to calculate the number of months between the start and end dates for each row.

Read How to Subtract Number of Days from a Date in Python?

Handle Edge Cases

Let us see how to handle some edge cases:

1. Partial Months

If you need to account for partial months, you can use the days attribute relativedelta to determine if a partial month should be counted as a full month. For instance, if the difference in days is 15 or more, you might want to round up to the next month.

from datetime import datetime
from dateutil.relativedelta import relativedelta

# Define the start and end dates
start_date = datetime(2023, 1, 15)
end_date = datetime(2024, 11, 13)

# Calculate the difference using relativedelta
difference = relativedelta(end_date, start_date)

# Calculate the total number of months, rounding up for partial months over 15 days
total_months = difference.years * 12 + difference.months
if difference.days >= 15:
    total_months += 1

print(f"The number of months between {start_date.date()} and {end_date.date()} is {total_months} months, accounting for partial months.")

Output:

The number of months between 2023-01-15 and 2024-11-13 is 22 months, accounting for partial months.

I have executed the above example and added the screenshot below.

How to Get Number of Months Between Two Dates in Python

Read How to Get the Day of the Week from a Date in Python?

Conclusion

In this tutorial, I helped you to learn how to get the number of months between two dates in Python. I covered some methods to achieve this task which may be using dateutil library in Python and using pandas for DataFrame operations in Python. We also learned how to handle edge cases.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.