Write a python program to calculate the number of days between two days.

Example:

Python comes with datetime module which can be used to find the number of days between two days. All we need to do is to import them into our program.

Method 1: Subtracting date objects

Form the two different date objects using date(YYYY,MM,DD) and subtract them. The subtraction result into a timedelta object which can be used to retrieve the number of days as shown below.

output: 39 days

Always remember to import “date” from “datetime” module first in the program.

Method 2: Using datetime.strptime()

datetime.strptime() method in python has the following syntax:

datetime.strptime strips the “date” based on the specified date_format and returns a date object, which in turn can be subtracted from another date object same as the above program to get “timedelta” object.

output: 39 days

Now let’s see an try to find out how many days have been left in this year. All we need to do is to subtract the date.today() from the last date of this year.

Run the above program by yourself and see what output you get.

That’s all for the date difference in python. If you have any doubts or suggestions and please comment below.

Leave a Reply