Вычисление разницы между датами python

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.

Читайте также:  Welcome sound css v34

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.

Читайте также:  Java exception setting error code

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

Источник

Python Difference Between Two Dates in Days

After reading this article, you’ll learn how to find the difference between two dates in Python. Also, we’ll see how to calculate the number of days between two dates and datetime objects.

Table of contents

How to Calculate Difference Between Two Dates in Days

Dates can be in any form, such as string, date object, or datetime object. we will see the example of all cases.

Python provides the datetime module to create and manipulate the date and time. The below steps show how to use the datetime module to calculate the difference between two dates in days.

  1. Import datetime modulePython datetime module provides various functions to create and manipulate the date and time. Use the from datetime import datetime statement to import a datetime class from a datetime module.
  2. Convert date string to a datetime object There may be a case in which dates are in a string format. Before calculating the difference in days, we need to convert both date strings to a datetime object.
    Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format .
    The format codes are standard directives for mentioning the format of the string for parsing. For example, the %Y/%m/%d format codes are for yyyy-mm-dd
  3. Subtract the date2 from date1 To get the difference between two dates, subtract date2 from date1. A result is a timedelta object. The timedelta represents a duration which is the difference between two dates, time, or datetime instances, to the microsecond resolution.
  4. Get a difference in days To get the number of days between two dates, use the timedelta.days attribute
  5. Get the difference in seconds To get a result in seconds, use the timedelta.seconds attribute
Читайте также:  Discord bot python code

Example: Days between two dates

from datetime import datetime # dates in string format str_d1 = '2021/10/20' str_d2 = '2022/2/20' # convert string to date object d1 = datetime.strptime(str_d1, "%Y/%m/%d") d2 = datetime.strptime(str_d2, "%Y/%m/%d") # difference between dates in timedelta delta = d2 - d1 print(f'Difference is days')
from datetime import datetime as dt res = (dt.strptime('2022/2/20', "%Y/%m/%d") - dt.strptime('2021/10/20', "%Y/%m/%d")).days

Difference between two date object

There are cases in which you receive dates in a date object instead of a string. In such cases, you can directly calculate the difference between them by performing the subtraction operation.

from datetime import date def get_difference(date1, date2): delta = date2 - date1 return delta.days d1 = date(2021, 10, 20) d2 = date(2022, 2, 20) days = get_difference(d1, d2) print(f'Difference is days')

Difference between two datetime object

We need to work with a datetime object instead of a date in some cases. The datetime object contains both date (year-month-day) and time (hours-minutes-seconds) information. Let’s see how to calculate the number of days between two datetime objects.

  • First, convert a datetime string to a datetime object using the strptime() function
  • Next, calculate the difference by subtracting datetime1 from datetime2 .
from datetime import datetime # datetime in string format str_dt1 = '2021/10/20 09:15:32.36980' str_dt2 = '2022/2/20 04:25:42.120450' # convert string to datetime dt1 = datetime.strptime(str_dt1, "%Y/%m/%d %H:%M:%S.%f") dt2 = datetime.strptime(str_dt2, "%Y/%m/%d %H:%M:%S.%f") # difference between datetime in timedelta delta = dt2 - dt1 print(f'Difference is days')

The Python timedelta object considers 24 hours as one day, and For calendar days, you’ll need to round down to the nearest day by removing the partial day on both sides. I.e., we need to set hour, minute, and seconds to zero in both datetime.

from datetime import datetime # datetime in string format str_dt1 = '2021/10/20 09:15:32.36980' str_dt2 = '2022/2/20 04:25:42.120450' # convert string to datetime dt1 = datetime.strptime(str_dt1, "%Y/%m/%d %H:%M:%S.%f") dt2 = datetime.strptime(str_dt2, "%Y/%m/%d %H:%M:%S.%f") rounded_dt1 = dt1.replace(hour=0, minute=0, second=0, microsecond=0) rounded_dt2 = dt2.replace(hour=0, minute=0, second=0, microsecond=0) delta = (rounded_dt2 - rounded_dt1) print(delta.days)

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

Источник

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