Using Python’s datetime module, it is simple to calculate the number of days between two dates. This article describes how to use Python to calculate the number of days between two dates.

Following is the example of how to calculate the no of days between two dates using python.

import datetime

date1 = datetime.date(2022, 3, 1)
date2 = datetime.date(2022, 3, 10)

delta = date2 - date1
num_days = delta.days

print(num_days)

Explanation :

First, we need to import the datetime module. It provides various classes and functions for working with dates and times.

Next, we need to create date objects for the two dates we want to compare. We can do this using the datetime.date() function. To this function, we’ll pass the year, month & day as an arguments.

Now that we have our date objects, we have to calculate the number of days between them. We can do this by subtracting one date from the other, which will give us a timedelta object representing the difference between the two dates.

Finally, we can get the number of days between the two dates by accessing the days attribute of the timedelta object.

Categorized in:

Tagged in: