Python Sort Date Dd Mm Yyyy

6 min read

Sorting dates stored as strings in the dd mm yyyy format is a common task in Python, but it often trips up beginners. If you try to sort a list like ["15 03 2024", "02 12 2023", "28 07 2022"] using the default sorted() function, you will get an unexpected order. The result may look random: "02 12 2023" might come before "15 03 2024", but "28 07 2022" could land in the middle. That is because Python compares strings lexicographically, character by character, not chronologically. Still, to sort dates correctly, you must convert each string into a real date object that Python understands. This article explains exactly how to do that, step by step, with clear examples and practical tips for handling real-world data That alone is useful..

Why Sorting Dates as Strings Fails

When you sort strings, Python compares the first character of each string, then the second, and so on. That means "01 01 2024" will be placed before "02 01 2023" because "01" is less than "02"—even though the second date is earlier in time. Because of that, for dates in dd mm yyyy format, the day comes first. The year, which should be the most significant part, is at the end. This mismatch between string order and chronological order is the root of the problem That's the whole idea..

To fix it, you need a sort key—a function that tells Python how to compare each item. The key should transform each date string into a value that sorts chronologically. The most reliable way is to convert the string into a datetime object using Python’s built-in datetime module The details matter here..

The Core Solution: Convert Strings to datetime Objects

Python’s datetime module provides the strptime method, which parses a string into a datetime object according to a specified format. For dd mm yyyy, the format code is "%d %m %Y". Here is how it works:

from datetime import datetime

date_string = "15 03 2024"
date_object = datetime.strptime(date_string, "%d %m %Y")
print(date_object)  # 2024-03-15 00:00:00

Once you have datetime objects, Python can compare them naturally. That said, a date in 2023 will always be less than a date in 2024, regardless of the day or month. This is the foundation for correct sorting That's the part that actually makes a difference..

Step-by-Step Guide to Sort Dates in dd mm yyyy Format

Follow these steps to sort a list of date strings from earliest to latest And that's really what it comes down to..

Step 1: Create Your List of Date Strings

Start with a sample list. Real data might come from a CSV file, a database, or user input Easy to understand, harder to ignore..

dates = [
    "15 03 2024",
    "02 12 2023",
    "28 07 2022",
    "01 01 2024",
    "10 10 2023"
]

Step 2: Define a Parsing Function

Create a small function that converts a single string into a datetime object. This function will serve as the sort key Less friction, more output..

def parse_date(date_str):
    return datetime.strptime(date_str, "%d %m %Y")

Step 3: Use sorted() with the Key Parameter

The sorted() function accepts a key argument. Pass your parsing function, and Python will sort the original strings based on the parsed dates Worth knowing..

sorted_dates = sorted(dates, key=parse_date)
print(sorted_dates)

Output:

['28 07 2022', '10 10 2023', '02 12 2023', '01 01 2024', '15 03 2024']

The list is now in chronological order. Notice that the original strings are preserved—only their order changes Not complicated — just consistent..

Sorting Dates in Place with list.sort()

If you want to sort the list directly without creating a new one, use the list.sort() method. It accepts the same key parameter Still holds up..

dates.sort(key=parse_date)
print(dates)

This modifies dates in place and returns None. Use this when you no longer need the original order.

Handling Invalid or Missing Dates

Real-world data is rarely perfect. You might encounter empty strings, None values, or malformed dates like "31 02 2024" (February 31 does not exist). If your parsing function raises an error, the entire sort will fail. To make your code strong, wrap the parsing logic in a try-except block and return a fallback value.

def safe_parse_date(date_str):
    try:
        return datetime.strptime(date_str, "%d %m %Y")
    except (ValueError, TypeError):
        return datetime.min  # or datetime.max, depending on desired order

Using datetime.On top of that, max places them at the end. minplaces invalid dates at the beginning. Think about it: choose the fallback that makes sense for your use case. Usingdatetime.You can also filter out invalid entries before sorting Practical, not theoretical..

Sorting Dates with Different Separators or Formats

Sometimes dates appear as "15-03-2024" or "15/03/2024". The same approach works—just adjust the format string.

  • For "15-03-2024", use "%d-%m-%Y".
  • For "15/03/2024", use "%d/%m/%Y".
  • For dates with leading zeros omitted (e.g., "5 3 2024"), use "%d %m %Y"—Python’s strptime handles single-digit days and months correctly.

If your data contains mixed separators, you may need to normalize the strings first or try multiple formats in a loop.

Advanced: Sorting Objects with Date Attributes

In object-oriented code, you might have a list of dictionaries or custom objects where the date is one attribute. For example:

records = [
    {"event": "A", "date": "15 03 2024"},
    {"event":

```python
    {"event": "B", "date": "02 12 2023"},
    {"event": "C", "date": "01 01 2024"},
]

To sort these records chronologically, define a key function that extracts the date string and parses it:

def record_date_key(record):
    return parse_date(record["date"])

sorted_records = sorted(records, key=record_date_key)

Alternatively, use a lambda for a more concise expression:

sorted_records = sorted(records, key=lambda r: parse_date(r["date"]))

For custom objects with a .date attribute, the pattern is the same:

class Event:
    def __init__(self, name, date_str):
        self.name = name
        self.date = date_str

events = [Event("A", "15 03 2024"), Event("B", "02 12 2023")]
sorted_events = sorted(events, key=lambda e: parse_date(e.date))

If your objects already store dates as datetime instances, you can sort directly without a parsing step—just use key=lambda e: e.date.

Sorting by Multiple Criteria

Sometimes you need a secondary sort key, such as sorting events by date and then by name. Return a tuple from your key function; Python compares tuples element by element Small thing, real impact. And it works..

sorted_records = sorted(
    records,
    key=lambda r: (parse_date(r["date"]), r["event"])
)

This sorts primarily by date and breaks ties alphabetically by event name. The same technique works for any combination of attributes Still holds up..

Performance Considerations

Parsing dates during sorting means the parsing function runs once per element (Python’s Timsort calls the key function exactly once per item). For large datasets, this is efficient. Still, if you sort the same list repeatedly, consider pre-parsing the dates into a new list of tuples or decorating your objects with a cached datetime attribute. This avoids redundant parsing and can significantly speed up repeated sorts.

Conclusion

Sorting date strings in Python is straightforward once you recognize that the built-in sorted() and list.Remember to handle malformed or missing dates gracefully with try-except blocks and sensible fallbacks, and adjust the format string to match your data’s separators and ordering. sort() functions accept a key parameter. The same pattern extends to dictionaries, custom objects, and multi-criteria sorts. Still, by supplying a function that converts each string into a datetime object, you let Python compare real dates rather than lexicographic text. With these techniques, you can reliably order chronological data in any Python application—from log analysis to event scheduling—without writing custom sorting algorithms.

Just Went Live

Fresh Out

More of What You Like

Interesting Nearby

Thank you for reading about Python Sort Date Dd Mm Yyyy. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home