Problem: Write a python program to calculate the number of days between two days.
Example:
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 in a timedelta object which can be used to retrieve the number of days as shown below.
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()
The datetime.strptime()
function in Python has the following syntax:
datetime.strptime("date", date_format)
The datetime.strptime()
function strips the “date” based on the specified date_format
and returns a date object.
We can use this object to subtract from another date object, similar to the above program to get timedelta
object.
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 try to find out how many days have been left in this year.
To do this, we have to subtract the date.today()
from the last date of this year.
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.