Write a Python Program to find number of days between two given dates?

In this post, we’ll learn how to write a Python program to find the number of days between two given dates.

There are several libraries in Python that can be used to calculate the difference between two dates, but in this post, we’ll be using the “date” module from the “datetime” library.

First, let’s start by importing the “date” module from the “datetime” library:

from datetime import date

Next, we’ll need to get the two dates for which we want to find the difference. We can get the current date using the “date.today()” method and we can get a specific date by creating a “date” object with the year, month, and day as arguments.

date1 = date.today()
date2 = date(2022, 12, 25)

Once we have the two dates, we can calculate the difference between them using the “date.toordinal()” method, which returns the proleptic Gregorian ordinal of a date, where January 1 of year 1 has ordinal 1.

This can be used to calculate the difference between two dates.

diff = date2.toordinal() - date1.toordinal()

Finally, we can print the number of days between the two dates.

print("Number of days between", date1, "and", date2, "is: ", diff)

Here is the complete code in one piece:

from datetime import date

date1 = date.today()
date2 = date(2022, 12, 25)
diff = date2.toordinal() - date1.toordinal()

print("Number of days between", date1, "and", date2, "is: ", diff)

Note:

  • The above solution will work correctly if date1 is before date2, if date2 is before date1 the result will be negative. So you can use abs() function to get the absolute value of difference.
  • The above code is not taking care of leap years, So it will not work correctly if one of the date is in February 29th. To handle this scenario you can use the ‘relativedelta’ class of the ‘dateutil’ library.

I hope this helps! Let me know if you have any questions.