File: reformat-date/solution.py

Date: 2026-06-06

Time: 18:41

reformat-date/solution.py

Purpose

This file solves LeetCode #1507: Reformat Date. It converts a human-readable date string in "Day Month Year" format (e.g., "20th Oct 2052") into the ISO-like "YYYY-MM-DD" format (e.g., "2052-10-20"). The file is self-contained: it holds both the solution class and its unit tests.

Key Components

Solution.reformatDate(date: str) -> str — The core method. It:

1. Defines a months dict mapping 3-letter abbreviations to zero-padded month numbers.

2. Splits the input into three tokens: day (with ordinal suffix), month abbreviation, year.

3. Strips the ordinal suffix from the day using rstrip("stndrdth").

4. Returns the formatted string with zfill(2) to ensure single-digit days get a leading zero.

TestReformatDate — Three test methods covering:

Patterns

Dependencies

Imports: Only unittest from the standard library — no external dependencies.

Imported by: The test_solution.py in the same directory imports Solution from this file. The large "Imported By" list in the prompt is misleading — those are *other* problems' test files, not actual importers of this module. They share the same structural pattern but don't reference this file's code.

Flow


"20th Oct 2052"
  → split() → ["20th", "Oct", "2052"]
  → rstrip("stndrdth") on "20th" → "20"
  → months["Oct"] → "10"
  → f"{2052}-{10}-{20}" → "2052-10-20"

For single-digit days like "6th": rstrip yields "6", then zfill(2) pads to "06".

Invariants

Error Handling

None. The solution trusts LeetCode's input guarantees. An invalid month abbreviation would propagate a KeyError; a completely non-numeric day string would produce garbage from zfill but not raise.

Beliefs