Find the difference between two dates in Python

In Python, ” datetime ” module is used to find the difference between two dates.

The ‘ datetime ‘ module is a versatile and powerful tool for handling and working with dates & times. It provides a wide range of functionality, from creating and formatting date and time objects to performing arithmetic operations.

Key Classes in ‘ datetime ‘ :

  1. ‘ datetime.date ‘
  2. ‘ datetime.time ‘
  3. ‘ datetime.datetime ‘
  4. ‘ datetime.timedelta ‘
  5. ‘ datetime.tzinfo ‘

Difference between two dates using ‘datetime’ module :

step  1:- Import the ‘ datetime ‘ module, which provides classes for manipulating dates.

Syntax :

from datetime import datetime

Step  2:- Define the two dates. Here you have to define the two dates using the ‘ datetime ‘ class.

syntax :

date1 = datetime(2023, 6, 20)
date2 = datetime(2024, 6, 20)

Step 3:- Calculate the difference. Subtract one ‘ datetime ‘ object from the other ‘datetime’ to get a ” timedelta ” object. ‘ timedelta ‘ refers to the difference between two dates or times.

Syntax :

difference = date2 - date1

Step 4:- Print the difference. The ‘ timedelta ‘ object has the property called days, which prints the difference in days.

Syntax : 

print(f"Difference: {difference.days} days")
Example Code 1 :
from datetime import datetime
first_date = date(2022, 11, 5)
last_date = date(2023, 11, 7)
delta = last_date - first_date
print(delta.days)
Output : 

367 days

The output for the provided code is 367 days. This is the number of days between November 5, 2022, and November 7, 2023.

Example Code 2 :
from datetime import datetime
first_datetime = datetime(2022, 11, 5, 12, 0, 0)  # yyyy, mm, dd, hh, mm, ss
last_datetime = datetime(2023, 11, 7, 15, 30, 0)
delta = last_datetime - first_datetime
print(f"Difference in days: {delta.days}")
print(f"Difference in seconds: {delta.seconds}")
print(f"Total difference in seconds: {delta.total_seconds()}")
Output :

Difference in days: 367
Difference in seconds: 12600
Total difference in seconds: 31708800.0

Difference in days: The number of full days between the two dates.

Difference in seconds: The remaining seconds after accounting for full days. Since the first datetime is at 12:00 PM and the last datetime is at 3:30 PM, this gives an additional 3 hours and 30 minutes, which is 12600 seconds (3 * 3600 + 30 * 60).

The total difference in seconds: The total difference including days and the remaining seconds, is calculated as 367×86400+12600367 \times 86400 + 12600.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top