Python datetime difference in years

Python: Get difference between two dates in years

In this article, we will discuss how to get the difference between two dates in years in python.

In python, the dateutil module provides a class relativedelta, which represents an interval of time. The relativedelta class has following attributes which tells about the duration,

  • Year
  • Month
  • Day
  • Hours
  • Minutes
  • Seconds
  • Microseconds

So, to calculate the difference between two dates in years, we can create a relativedelta object to represent the interval between two given dates. Then we can fetch the Year attribute of relativedelta object, it will tell us the difference between two dates in years. Let’s understand with some examples,

Python Example 1: Get difference between two dates in years

If you have some existing datetime objects instead of strings, then we can get the difference between those two datetime objects in years like this,

from datetime import datetime from dateutil import relativedelta date_1 = datetime(2021, 7, 2) date_2 = datetime(2032, 3, 24) # Get the interval between two dates diff = relativedelta.relativedelta(date_2, date_1) print('Difference between dates in years: ', diff.years) print('Complete Difference between two dates: ') print(diff.years , ' years, ', diff.months, ' months and ', diff.days, ' days')

Frequently Asked:

Difference between dates in years: 10 Complete Difference between two dates: 10 years, 8 months and 22 days

Python Example 2: Get difference between two dates in years

Suppose we have two dates in string format. We can convert them to datetime objects using datetime.strptime() function. Then we will get the interval between two dates as a relativedelta object. Then using the years property of relativedelta object, we will fetch the years in between the two dates. For example,

from datetime import datetime from dateutil import relativedelta from datetime import datetime date_1 = '2/7/2021' date_2 = '24/7/2023' start = datetime.strptime(date_1, "%d/%m/%Y") end = datetime.strptime(date_2, "%d/%m/%Y") # Get the interval between two dates diff = relativedelta.relativedelta(end, start) print('Difference between dates in years: ', diff.years) print('Complete Difference between two dates: ') print(diff.years , ' years, ', diff.months, ' months and ', diff.days, ' days')
Difference between dates in years: 2 Complete Difference between two dates: 2 years, 0 months and 22 days

Python Example 3: Get difference between two timestamps in years

If we have complete timestamps instead of dates only, then we can convert them to datetime objects using datetime.strptime() function and specific format string as argument. Then we will get the interval between two timestamps as a relativedelta object. Then using the years property of relativedelta object, we will fetch the years in between the two timestamps. For example,

from datetime import datetime from dateutil import relativedelta from datetime import datetime date_1 = '24/7/2021 11:13:08.230010' date_2 = '1/9/2023 11:14:18.333338' date_format_str = '%d/%m/%Y %H:%M:%S.%f' start = datetime.strptime(date_1, date_format_str) end = datetime.strptime(date_2, date_format_str) # Get the interval between two dates diff = relativedelta.relativedelta(end, start) print('Difference between dates in years: ', diff.years) print('Complete Difference between two dates: ') print(diff.years , ' years, ', diff.months, ' months and ', diff.days, ' days')
Difference between dates in years: 2 Complete Difference between two dates: 2 years, 1 months and 8 days

We learned that, in python how to get the difference between two dates in years.

Читайте также:  Java network connection reset

Источник

Calculate Number of Years, Months & Days Between Two Dates in Python (2 Examples)

TikTok Icon Statistics Globe

In this tutorial you’ll learn how to calculate the number of years, months, and days between two dates using the Python programming language.

The table of content is structured as follows:

Example Data & Add-On Libraries

First we have to import date from the datetime module and relativedelta from the dateutil module:

from datetime import date from dateutil import relativedelta

Then, let’s construct some sample dates to use in our example:

date_1 = date(1991, 10, 20) date_2 = date(2001, 6, 15)

Date objects have year, month and day fields. They can be used to get more specific information about the date.

print(date_1.year, date_1.month, date_1.day) print(date_2.year, date_2.month, date_2.day) # 1991 10 20 # 2001 6 15

Example 1: Calculate the Difference Between Two Dates in Years, Months & Days Format

Note1: We can think of it as date_diff = date_2 – date_1 to remember the parameter order.

Note2: The following if else statement can be used to avoid negative difference results which may occur due to dates being unknown at the start of the program.

if date_1  date_2: date_diff = relativedelta.relativedelta(date_2, date_1) else: date_diff = relativedelta.relativedelta(date_1, date_2) years = date_diff.years # 9 months = date_diff.months # 7 days = date_diff.days # 26 print('<> years <> months <> days'.format(years, months, days)) # 9 years 7 months 26 days

The printed output would be “-9 years -7 months -26 days” if the dates were entered in the wrong order.

Example 2: Calculate Your Lifetime

It’s also possible to calculate your personal lifetime in years, months, and days using Python code. Let’s assume your date of birth is the 18th of May 1999:

today = date.today() # 2022 11 3 birthday = date(1999, 5, 18) # 1999 5 18

Next, we can apply the relativedelta function to calculate the lifetime:

date_diff = relativedelta.relativedelta(today, birthday) years = date_diff.years # 23 months = date_diff.months # 5 days = date_diff.days # 16 print('Congrats! You have been alive for <> years <> months <> days'.format(years, months, days)) # Congrats! You have been alive for 23 years 5 months 16 days

Video, Further Resources & Summary

Do you need more explanations on how to compute time differences using Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

In the video, we explain how to return the difference between two dates in years, months, and days using the Python syntax of the present tutorial.

The YouTube video will be added soon.

Furthermore, you could have a look at some of the other tutorials on Statistics Globe:

This post has shown how to get the time difference between two dates in years, months, and days. If you have any further questions, you might leave a comment below.

Ömer Ekiz Informatics Expert

This page was created in collaboration with Ömer Ekiz. You may have a look at Ömer’s author page to read more about his academic background and the other articles he has written for Statistics Globe.

Источник

Python Difference Between Two Dates in Months and Years

After reading this article, you’ll learn how to find years and months between two dates in Python.

Table of contents

How to calculate years and months between two dates

Python dateutil module provides a relativedelta class, representing an interval of time. For example, we can find the difference between two dates in year, months, days, hours, minutes, seconds, and microseconds using the relativedelta class. The Below steps show how to determine the number of years and months between two dates or datetime objects.

  1. Import dateutil module The dateutil is a third-party module that provides powerful extensions to the standard datetime module, available in Python.
  2. Convert date string to a datetime object If a date is in a string format, we need to convert a string to a datetime object before calculating the difference in months. Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . For example, the string can be in the format of yyyy-mm-dd .
  3. Create a relativedelta object Create a relativedelta object that represents the interval between two given dates. Use the relativedelta(end_date, start_date) function of a dateutil module to create a relativedelta object.
  4. Get Years, Months, and Days between two dates Use the relativedelta.years attribute to get years.
    Next, Use the relativedelta.months to get months.
    In the end, use relativedelta.days to get days.
  5. Get only months between two dates Use the relativedelta.months + relativedelta.years * 12 formula to get the total months between two dates.

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

Let’s assume we have two dates, ’14/8/2019′ and ’16/3/2022′. After executing the below example, we should get the difference of 2 Years, 7 months, and 2 days between two dates.

from datetime import datetime from dateutil import relativedelta # get two dates d1 = '14/8/2019' d2 = '16/3/2022' # convert string to date object start_date = datetime.strptime(d1, "%d/%m/%Y") end_date = datetime.strptime(d2, "%d/%m/%Y") # Get the relativedelta between two dates delta = relativedelta.relativedelta(end_date, start_date) print('Years, Months, Days between two dates is') print(delta.years, 'Years,', delta.months, 'months,', delta.days, 'days')
Years, Months, Days between two dates is 2 Years, 7 months, 2 days

Example: Get Only Months between two dates

Note: The relativedelta.months return the relative difference, i.e., from 0 to 12. So to get an absolute number, we need to calculate the number of years between two dates, multiply them by 12 and add them to relativedelta.months .

from datetime import datetime from dateutil import relativedelta # get two dates d1 = '14/8/2019' d2 = '16/3/2022' # convert string to date object start_date = datetime.strptime(d1, "%d/%m/%Y") end_date = datetime.strptime(d2, "%d/%m/%Y") # Get the relativedelta between two dates delta = relativedelta.relativedelta(end_date, start_date) # get months difference res_months = delta.months + (delta.years * 12) print('Total Months between two dates is:', res_months) 
Total Months between two dates is: 31

Difference between two dates in months using datetime module

Instead of using the dateutil module, we can use the built-in datetime module to get calendar months between two dates.

Use the below formula to calculate.

res = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month)
from datetime import datetime date_1 = '24/12/2021' date_2 = '26/3/2022' start = datetime.strptime(date_1, "%d/%m/%Y") end = datetime.strptime(date_2, "%d/%m/%Y") res = (end.year - start.year) * 12 + (end.month - start.month) print('Difference between dates in months:', res)
Difference between dates in months: 3

Use the datetime module when you need a difference in the calendar month. Don’t use the datetime module to calculate the exact months between two dates.

For example, the difference between ’30/1/2022′ and ‘1/2/2022’ is 2 days, but the above example shows 1 month. So always use the dateutil module to get the correct results.

Example 1: Datetime module

from datetime import datetime from dateutil import relativedelta start = datetime.strptime('30/1/2022', "%d/%m/%Y") end = datetime.strptime('1/2/2022', "%d/%m/%Y") res = (end.year - start.year) * 12 + (end.month - start.month) print('Months between two dates is:', res) # Output 1

Example 2: Dateutil module

from datetime import datetime from dateutil import relativedelta start_date = datetime.strptime('30/1/2022', "%d/%m/%Y") end_date = datetime.strptime('1/2/2022', "%d/%m/%Y") delta = relativedelta.relativedelta(end_date, start_date) res_months = delta.months + (delta.years * 12) print('Months between two dates is:', res_months) # Output 0

Calculate months between two datetime objects

There are cases in which you receive dates in a datetime object instead of a string. In such cases, you don’t need to convert them. You can directly calculate the difference between them.

from datetime import datetime # datetime in year-month-day-hour-minute-second-microsecond format start = datetime(2021, 10, 20, 9, 15, 32, 36980) end = datetime(2022, 2, 20, 4, 25, 42, 120450) res = (end.year - start.year) * 12 + (end.month - start.month) print('Difference between dates in months:', res) 
Difference between dates in months: 4

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

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

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 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Оцените статью