find the number of days between two dates in python

In this article we are going to find the number of days between two dates using python. This can be done easily using a builtin python module called datetime. This eliminates the requirement of any other external libraries to perform this simple task. Let us first take a look at the datetime module in python.

datetime module in python

A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.

Let us take a look at this with a simple example. The following code snippet will give you the current date and time.

current date and time in python

The output of the above code snippet is,

2020-07-05 12:43:37.220118

The date contains year, month, day, hour, minute, second, and microsecond.

Let us get to our code.

Steps involved

The following steps are involved in finding the difference between the two dates.

  1. Get the first date in (year, month, day) format.
  2. Get the second date also in the same format.
  3. Convert them to datetime object.
  4. Find the difference between the two datetime objects.
  5. This will return us a datetime class. We can call the days object from this class to get the difference as an integer value.

Code

The following code snippet demonstrates the usage of datetime module to get the difference between any two dates.

The output of this code is ,

8

The difference between the two dates is printed.

If you want to know more about the datetime modules and the methods associated with it take a look at this official documentation from python.

Happy coding!