In Python, comparing dates is straightforward with the help of the datetime module. You can use basic comparison operators like <, >, ==, and != to compare two date or datetime objects directly. Below are a few common and practical ways to compare and sort dates in Python.
Basic Date Comparison
You can directly compare two datetime objects using standard comparison operators.
from datetime import datetime
d1 = datetime(2018, 5, 3)
d2 = datetime(2018, 6, 1)
print("d1 > d2:", d1 > d2)
print("d1 < d2:", d1 < d2)
print("d1 != d2:", d1 != d2)
Output
d1 > d2: False d1 < d2: True d1 != d2: True
Explanation:
- datetime() creates a date-time object.
- operators like >, <, and != work directly on datetime objects.
Sorting a List of Dates
Dates can be stored in a list and sorted using the sort() method.
from datetime import date, timedelta
dates = [
date.today(),
date(2015, 6, 29),
date(2011, 4, 7),
date(2011, 4, 7) + timedelta(days=25)
]
dates.sort()
for d in dates:
print(d)
Output
2011-04-07 2011-05-02 2015-06-29 2025-04-22
Explanation:
- date.today() returns the current date.
- timedelta(days=25) adds days to a date.
- sort() arranges the list of dates in ascending order.
Using timedelta for Comparison
We can also use subtraction between date objects and compare the result using timedelta.
from datetime import date, timedelta
d1 = date(2022, 4, 1)
d2 = date(2023, 4, 1)
print("d1 > d2:", d1 - d2 > timedelta(0))
print("d1 < d2:", d1 - d2 < timedelta(0))
print("d1 != d2:", d1 != d2)
Output
d1 > d2: False d1 < d2: True d1 != d2: True
Explanation:
- Subtracting two dates returns a timedelta object.
- Comparing with timedelta(0) shows which date is earlier/later.
- != checks if the dates are different.
Also read: sort(), timedelta, datetime object.