How to compare date strings in Python?

Python's datetime module makes comparing dates straightforward by supporting all comparison operators (<, >, <=, >=, ==, !=). This is essential for date validations, sorting, and conditional logic in your applications.

Basic Date Comparison

Here's how to compare datetime objects using comparison operators ?

from datetime import datetime, timedelta

today = datetime.today()
yesterday = today - timedelta(days=1)

print("Today:", today.strftime("%Y-%m-%d"))
print("Yesterday:", yesterday.strftime("%Y-%m-%d"))
print()
print("today < yesterday:", today < yesterday)
print("today > yesterday:", today > yesterday)
print("today == yesterday:", today == yesterday)
Today: 2024-01-15
Yesterday: 2024-01-14

today < yesterday: False
today > yesterday: True
today == yesterday: False

Comparing Date Strings

When working with date strings, convert them to datetime objects first for accurate comparison ?

from datetime import datetime

# Date strings in different formats
date1_str = "2024-01-15"
date2_str = "2024-01-20"
date3_str = "15/01/2024"

# Convert to datetime objects
date1 = datetime.strptime(date1_str, "%Y-%m-%d")
date2 = datetime.strptime(date2_str, "%Y-%m-%d")
date3 = datetime.strptime(date3_str, "%d/%m/%Y")

print("date1 < date2:", date1 < date2)
print("date1 == date3:", date1 == date3)
print("date2 > date3:", date2 > date3)
date1 < date2: True
date1 == date3: True
date2 > date3: True

Practical Example: Age Verification

Here's a practical example checking if someone is old enough ?

from datetime import datetime

def is_old_enough(birth_date_str, min_age=18):
    birth_date = datetime.strptime(birth_date_str, "%Y-%m-%d")
    today = datetime.today()
    age_in_days = (today - birth_date).days
    age_in_years = age_in_days / 365.25
    
    return age_in_years >= min_age

# Test with different birth dates
birth_dates = ["2000-05-15", "2010-03-20", "1995-12-01"]

for birth_date in birth_dates:
    result = is_old_enough(birth_date)
    print(f"Born {birth_date}: Old enough? {result}")
Born 2000-05-15: Old enough? True
Born 2010-03-20: Old enough? False
Born 1995-12-01: Old enough? True

Comparison Summary

Operator Description Example Usage
< Less than Check if date is before another
> Greater than Check if date is after another
== Equal to Check if dates are the same
<= Less than or equal Check deadline compliance
>= Greater than or equal Check minimum date requirements

Conclusion

Always convert date strings to datetime objects using strptime() before comparing. Python's datetime comparison operators make date validation and sorting intuitive and reliable.

Updated on: 2026-03-24T19:33:10+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements