Find the difference between dates in Python Example

Hey, this is a quick example for how to compare and calculate the difference between two dates in python. Here are the steps using the standard library datetime package.

  1. Get the date objects by parsing them from strings as follows.
  2. Subtract the two dates (d2-d1) to return a TimeDelta object.
  3. Use the timedelta.days property to return the number of days between the two date objects. Thats it !!!
from datetime import datetime

# dates in string format
d1 = '2022/10/20'
d2 = '2022/2/20'

# convert string to date object
date1 = datetime.strptime(d1, "%Y/%m/%d")
date2 = datetime.strptime(d2, "%Y/%m/%d")

# difference between dates in timedelta
delta = date2 - date1
print(f'Difference is {delta.days} days')

Check Also

Best AI tools list