Sort date strings

EasyDatetime Programs · 16 of 20

Write a Python program to sort a list of date strings in date order.

Advertisement
Input
["15-08-2026", "26-01-2026", "02-10-2026"]
Output
['26-01-2026', '15-08-2026', '02-10-2026']

Approach

  1. Sort with a key that parses each string.

Solution

Python
from datetime import datetime dates = ["15-08-2026", "26-01-2026", "02-10-2026"]print(sorted(dates, key=lambda s: datetime.strptime(s, "%d-%m-%Y")))
Output
['26-01-2026', '15-08-2026', '02-10-2026']

Line by line

Line 4

Sorting the raw strings would compare day numbers first and give the wrong order.

Learn the concept

New to this topic? Read the lesson, then come back.

More datetime programs

← All 20 Datetime Programs

Leave a Comment