Python difference between two dates in days

Difference between two dates in days , weeks, Months and years in Pandas python

Difference between two date columns in pandas can be achieved using timedelta function in pandas. In this section we will be covering difference between two dates in days, week , and year in pandas python with example for each. We will be explaining how to get

  • Difference between two dates in days pandas dataframe python
  • Difference between two dates in weeks pandas dataframe python
  • Difference between two dates in Months pandas dataframe python
  • Difference between two dates in years pandas dataframe python

First lets create a dataframe with two dates.

import pandas as pd import numpy as np import datetime from dateutil.relativedelta import relativedelta from datetime import date date1 = pd.Series(pd.date_range('2012-1-1 12:00:00', periods=7, freq='M')) date2 = pd.Series(pd.date_range('2013-3-11 21:45:00', periods=7, freq='W')) df = pd.DataFrame(dict(Start_date = date1, End_date = date2)) print(df)

so the resultant dataframe will be

Читайте также:  Typescript promise reject type

Difference between two dates in days , weeks, Months and years in Pandas python 1

Difference between two dates in days – pandas dataframe python

  • First line calculates the difference between two dates
  • Second line converts the difference in terms of days (timedelta64(1,’D’)- D indicates days)
df['diff_days'] = df['End_date'] - df['Start_date'] df['diff_days']=df['diff_days']/np.timedelta64(1,'D') print(df)

so the resultant dataframe will be

Difference between two dates in days , weeks, Months and years in Pandas python 1

Difference between two dates in weeks – pandas dataframe python

  • First line calculates the difference between two dates
  • Second line converts the difference in terms of weeks (timedelta64(1,’W’)- W indicates weeks)
df['diff_weeks'] = df['End_date'] - df['Start_date'] df['diff_weeks']=df['diff_weeks']/np.timedelta64(1,'W') print(df)

so the resultant dataframe will be

Difference between two dates in days , weeks, Months and years in Pandas python 1

Difference between two dates in Months – pandas dataframe python

  • First line calculates the difference between two dates
  • Second line converts the difference in terms of Months (timedelta64(1,’M’)- capital M indicates Months)
df['diff_months'] = df['End_date'] - df['Start_date'] df['diff_months']=df['diff_months']/np.timedelta64(1,'M') print(df)

so the resultant dataframe will be

Difference between two dates in days , weeks, Months and years in Pandas python 1

Difference between two dates in Years – pandas dataframe python

  • First line calculates the difference between two dates
  • Second line converts the difference in terms of Years (timedelta64(1,’Y’)- Y indicates years)
df['diff_years'] = df['End_date'] - df['Start_date'] df['diff_years']=df['diff_years']/np.timedelta64(1,'Y') print(df)

so the resultant dataframe will be

Difference between two dates in days , weeks, Months and years in Pandas python 1

Author

With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark. View all posts

Источник

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

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

Источник

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.

Источник

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