← Back to Articles
Tutorial

Calculate Date Difference in Python

Learn how to calculate date difference in Python with examples and best practices to avoid common mistakes.

Calculating the difference between two dates is a common task in Python programming, essential for applications requiring date-based calculations like age, duration, or time intervals.

Python offers several ways to calculate date differences, primarily using the 'datetime' module. By importing 'datetime' and using 'date' objects, you can easily subtract one date from another to get the difference in days.

When calculating date differences, consider using 'timedelta' for more complex calculations like adding days or managing time zones. It is best practice to handle exceptions for invalid dates.

A common mistake is not accounting for edge cases like leap years or different month lengths. Always validate input dates and handle exceptions to ensure accurate calculations.

Code Examples

Example 1

from datetime import date

d1 = date(2023, 10, 1)
d2 = date(2023, 10, 15)
difference = d2 - d1
print(difference.days)

Example 2

from datetime import datetime, timedelta

date_format = "%Y-%m-%d"
start_date = datetime.strptime("2023-10-01", date_format)
end_date = datetime.strptime("2023-10-15", date_format)
difference = end_date - start_date
print(difference.days)

More Python Tutorials