- Python: Get difference between two dates in days
- Python Example 1: Get difference between two dates in days
- Frequently Asked:
- Python Example 2: Get difference between two dates in days
- Python Example 3: Get difference between two datetimes in days
- Python Example 4: Get difference between two datetimes in days
- Python Example 5: Get difference between two dates in days using pandas
- Related posts:
- Share your love
- Leave a Comment Cancel Reply
- Terms of Use
- Disclaimer
- Python Difference Between Two Dates in Days
- Table of contents
- How to Calculate Difference Between Two Dates in Days
- Example: Days between two dates
- Difference between two date object
- Difference between two datetime object
- About Vishal
- Related Tutorial Topics:
- Python Exercises and Quizzes
Python: Get difference between two dates in days
In this article, we will discuss how to get the difference between two dates in days in python.
Python provides a module datetime for manipulation of date and time. It consists of following classes,
- datetime.date : An object of date class specifies a date using year, month and day
- datetime.time : An object of time class specifies a timestamp using hour, minute, second, microsecond, and tzinfo.
- datetime.datetime: An object of datetime is a combination of a date and a time.
- datetime.timedelta: A duration, that represents the difference between two dates or times or datetimes.
- datetime.tzinfo: It contains the time zone information.
Now to get the difference between two dates in python, we will use the datetime module. First we will create start and end datetime objects from the string dates. Then we will subtract the datetime objects to get the duration as the datetime.timedelta object. Then using the properties of timedelta object, we will fetch the days in between the two dates. Let’s understand with some examples,
Python Example 1: Get difference between two dates in days
from datetime import datetime date_1 = '2/7/2021' date_2 = '24/7/2021' start = datetime.strptime(date_1, "%d/%m/%Y") end = datetime.strptime(date_2, "%d/%m/%Y") # get the difference between wo dates as timedelta object diff = end.date() - start.date() print('Difference between dates in days:') print(diff.days)
Difference between dates in days: 22
The different between ’24/7/2021′ and ‘2/7/2021’ is 22 days
Frequently Asked:
How did it work ?
We createed the two datetime objects from the two dates in the string format, by passing the date and it’s format in the strptime() function. Then we subtracted these two datetime objects and got the datetime.timedelta object, which represents the duration between two dates. The timedelta class has a member variable days, which represents the number of days in this duration. We used that fetch the difference between two dates in days.
Python Example 2: Get difference between two dates in days
Let’s checkout an another example, where both dates are more than 2 years apart,
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 difference between two dates as timedelta object diff = end.date() - start.date() print('Difference between dates in days:') print(diff.days)
Difference between dates in days: 752
The different between ’24/7/2023′ and ‘2/7/2021’ is 752 days
Python Example 3: Get difference between two datetimes in days
Let’s checkout an another example, where instead of date strings, we have complete timestamps in string and we want the difference between these two timestamps in days. For example,
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 difference between two dates as timedelta object diff = end.date() - start.date() print('Difference between dates in days:') print(diff.days)
Difference between dates in days: 769
Python Example 4: Get difference between two datetimes in days
If you have some existing datetime objects instead of string then we can get the difference between those two datetime objects in days like this,
from datetime import datetime date_1 = datetime(2021, 7, 2) date_2 = datetime(2021, 7, 24) # get the difference between two datetimes as timedelta object diff = date_2 - date_1 print('Difference between dates in days:') print(diff.days)
Difference between dates in days: 22
Python Example 5: Get difference between two dates in days using pandas
Suppose we have two dates in string format. We can convert them to datetime object using pandas.to_datetime() function. Then we will subtract the datetime objects to get the duration in the datetime.timedelta object. Then using the properties of timedelta object, we will fetch the days in between the two dates. For example,
import pandas as pd from datetime import datetime date_1 = '2/7/2021' date_2 = '24/7/2021' start = pd.to_datetime(date_1, format='%d/%m/%Y') end = pd.to_datetime(date_2, format='%d/%m/%Y') # get the difference between two datetimes as timedelta object diff = end - start print('Difference between dates in days:') print(diff.days)
Difference between dates in days: 22
The different between two dates is 22 days.
We learned that, in python how to get the difference between two dates in days.
Related posts:
Share your love
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
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.
- 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.
- 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 - 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.
- Get a difference in days To get the number of days between two dates, use the timedelta.days attribute
- 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
Related Tutorial Topics:
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