- 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: Get Number of Days Between Dates
- Creating a Datetime Object
- Get Number of Days Between Dates in Python
- Adding and Subtracting Days Using TimeDelta
- Free eBook: Git Essentials
- Conclusion
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: Get Number of Days Between Dates
In this tutorial, we’ll take a look at how to get the number of days between two dates in Python.
We’ll be using the built-in datetime package, that allows you to really easily work with datetime objects in Python.
Creating a Datetime Object
As datetime is a built-in module, you can access it right away by importing it at the top of your Python file.
You can construct datetime objects in a few different ways:
from datetime import datetime date_string = "1 January, 2021" now = datetime.now() # Create Datetime based on system clock dt1 = datetime(day=1, month=1, year=2021) # Create Datetime with given arguments dt2 = datetime.strptime(date_string, "%d %B, %Y") # Create Datetime from String
There are certain rules to follow when it comes to Converting Strings to Datetime in Python.
Get Number of Days Between Dates in Python
Trying to measure the numbers of days between dates without using the datetime module is a deceptively complex task — between accounting for leap years and the number of days in each month, trying to create your own implementation is nonsensical.
With datetime however, it becomes trivial.
You can simply subtract a date or datetime from each other, to get the number of days between them:
from datetime import datetime date1 = datetime.now() date2 = datetime(day=1, month=7, year=2021) timedelta = date2 - date1 print(timedelta)
This returns a timedelta object, which contains days , seconds and microseconds and represents the duration between any two date / time or datetime objects.
Printing this object will return the days, hours, minutes, seconds and microseconds to that event:
If you’re not interested in some of these metrics, you can specify which of them you’d like to access with timedelta.days , timedelta.seconds and timedelta.microseconds :
now = datetime.now() new_years = datetime(day=1, month=1, year=2022) countdown = new_years - now print('Today is: ', now) print('New Year is on: ', new_years) print('Days until New Years: ', countdown.days)
Here, we’ve assigned the days between now and new_years into countdown , which is a timedelta object.
Then, we can simply access the days parameter of that object to get the number of days between them. This results in:
Today is: 2021-02-01 18:35:12.272524 New Year is on: 2022-01-01 00:00:00 Days until New Years: 333
Adding and Subtracting Days Using TimeDelta
What if instead of trying to subtract two known dates from each other, you wanted to add or subtract a time-frame? For example, a customer subscribed to your service for a monthly fee. You’ll want to remind them to renew it after 30 days.
You can construct a time-frame for those 30 days, using timedelta and add or subtract that from any other datetime object:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
from datetime import datetime, timedelta now = datetime.now() thirty_days = timedelta(days=30) print('In 30 days: ', now + thirty_days) print('30 days ago: ', now - thirty_days)
In 30 days: 2021-03-03 18:41:49.922082 30 days ago: 2021-01-02 18:41:49.922082
This is an incredibly useful feature when trying to implement scheduling, or retrieving database entries based on a moving window (such as the trailing 30 days).
Conclusion
In this tutorial, we’ve covered everything you need to know about getting the number of days between two dates in Python.
We’ve worked with datetime objects and timedelta to achieve this functionality.