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.
The output of the above code snippet is,
The date contains year, month, day, hour, minute, second, and microsecond.
Let us get to our code.
The following steps are involved in finding the difference between the two dates.
- Get the first date in (year, month, day) format.
- Get the second date also in the same format.
- Convert them to datetime object.
- Find the difference between the two datetime objects.
- This will return us a datetime class. We can call the days object from this class to get the difference as an integer value.
The following code snippet demonstrates the usage of datetime module to get the difference between any two dates.
The output of this code is ,
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.