Bird
Raised Fist0
PythonHow-ToBeginner · 3 min read

How to Compare Two Dates in Python: Simple Guide

To compare two dates in Python, use the datetime.date or datetime.datetime objects and compare them directly with comparison operators like <, >, or ==. These objects support natural date comparisons based on year, month, and day.
📐

Syntax

Use the datetime module to create date objects. Then compare them using operators:

  • date1 < date2: True if date1 is before date2
  • date1 > date2: True if date1 is after date2
  • date1 == date2: True if both dates are the same
python
from datetime import date

# Create two date objects
date1 = date(2023, 5, 10)
date2 = date(2023, 6, 15)

# Compare dates
print(date1 < date2)  # True
print(date1 > date2)  # False
print(date1 == date2) # False
Output
True False False
💻

Example

This example shows how to compare two dates and print which one is earlier, later, or if they are the same.

python
from datetime import date

date1 = date(2024, 4, 20)
date2 = date(2024, 4, 25)

if date1 < date2:
    print(f"{date1} is before {date2}")
elif date1 > date2:
    print(f"{date1} is after {date2}")
else:
    print(f"{date1} and {date2} are the same date")
Output
2024-04-20 is before 2024-04-25
⚠️

Common Pitfalls

Common mistakes include:

  • Comparing date strings instead of date objects, which compares text, not dates.
  • Mixing datetime.date and datetime.datetime objects without care, which can cause unexpected results.
  • Not importing the datetime module or creating dates incorrectly.
python
from datetime import datetime, date

# Wrong: comparing strings
str_date1 = "2023-05-10"
str_date2 = "2023-06-15"
print(str_date1 < str_date2)  # True but compares text, not dates

# Right: convert strings to date objects
correct_date1 = datetime.strptime(str_date1, "%Y-%m-%d").date()
correct_date2 = datetime.strptime(str_date2, "%Y-%m-%d").date()
print(correct_date1 < correct_date2)  # True, compares dates properly
Output
True True
📊

Quick Reference

Tips for comparing dates in Python:

  • Use datetime.date or datetime.datetime objects for accurate comparisons.
  • Use comparison operators: <, >, ==, <=, >=.
  • Convert date strings to date objects before comparing.
  • Remember that datetime.datetime includes time, so two dates with different times may not be equal.
✅

Key Takeaways

Use datetime.date or datetime.datetime objects to compare dates accurately.
Compare dates with standard operators like <, >, and == for clear results.
Always convert date strings to date objects before comparing.
Be careful mixing date and datetime objects to avoid unexpected results.