Write a python program to calculate the number of days between two days.
Example:
1 2 | Input: 8/18/2008 9/26/2008 Output: 39 days |
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.
1 2 3 4 5 6 7 | from datetime import date d0 = date(2008, 8, 18) d1 = date(2008, 9, 26) delta = d1 - d0 print(delta.days,"days") |
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:
1 | datetime.strptime("date",date_format) |
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.
1 2 3 4 5 6 7 8 9 10 | from datetime import datetime #specify date format date_format = "%m/%d/%Y" a = datetime.strptime('8/18/2008', date_format) b = datetime.strptime('9/26/2008', date_format) delta = b - a print(delta.days,"days") |
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.
1 2 3 4 5 6 7 | from datetime import date a = date.today() b = date(2020, 12, 31) delta = b - a print(delta.days,"days left in 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.