Compare and sort date values instead of comparing ambiguous text.
How It Works
date objects and consistently aware datetimes have chronological comparison behavior. ISO date strings may sort lexically in restricted forms, but locale-formatted strings often do not. Choose compatible date/time types before sorting.
Step-by-Step Example
from datetime import date
order_dates = [date(2026, 10, 20), date(2026, 9, 1), date(2026, 10, 17)]
print([value.isoformat() for value in sorted(order_dates)])
Understanding the Example
- The expression '[date(2026, 10, 20), date(2026, 9, 1), date(2026, 10, 17)]' supplies the value stored as 'order_dates'. This value is then used or checked by the later statements.
- The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.
A successful run of this example prints the following output:
['2026-09-01', '2026-10-17', '2026-10-20']
Where This Fits in a Real Program
For event timestamps, distinguish the displayed local clock from the instant that it represents. Store or exchange an unambiguous aware value, then convert it when displaying it to a user. For repeated calendar appointments, use a geographic timezone so daylight-saving rules are not lost.
Practice: Try It Yourself
An aware datetime comparison identifies absolute ordering across UTC offsets.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Sorting DD/MM/YYYY strings lexically and expecting chronological order.
- Sort a list of ISO date strings after converting each to a date.
Key Takeaways
- Compare and sort date values instead of comparing ambiguous text.
- date objects and consistently aware datetimes have chronological comparison behavior.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.