How to Calculate the Number of Days Between 2 Dates in Python



Python


In this article, we show how to calculate the number of days between 2 dates in Python.

We do this using the datetime module in Python.

The datetime module is built-in to the Python software when you download it from Python.org. Therefore, you do not have to install but simply import it into your code.

Being able to calculate the number of days between 2 dates is useful. For example, a person may wish to know how many days there are until his/her graduation, vacation, birthday, or some type of special event.

So the datetime module is very dynamic in that it can do calculations such as adding a number of days to a date or subtracting the number of days to a certain date.

In the code below, we get today's date and then we choose a future date, let's say January 7, 2021. From the time of this code, today's date is 11/18/2020 (November 18, 2020). We show how to calculate in code the number of days that exist between these 2 dates.



So the first thing we have to is import the datetime module. The datetime module allows us to work with dates in Python. All the dates we create in our code are datetime objects.

Next, we create a variable, todaysdate, and set it equal to today's date. This will contain the current year, month, and day, along with the hours and seconds.

Next, we create another variable, mytrip, which represents the date of a future trip that I am taking. This is on 1/7/2021.

To create a datetime object in Python, order must be adhered to. You first must specify the year, then the month, then the day.

We then take the trip date minus today's date and then use the days attribute to get the number of days between the 2 dates.

We see that there are 49 days between today's date of 11/18/2020 to 1/7/2021.

We don't have to manually count the days, as Python's datetime module has the versatility to do this for us.

And this is how we can calculate the number of days between two dates in Python.


Related Resources

How to Create a Zip File in Python

How to Extract All Files and Folders from a Zip File in Python

How to Read the Contents of a Zip File in Python



HTML Comment Box is loading comments...