Data Analyst Interview
Menu
Browse in your language. All mock interviews, preparation sessions and feedback are in English only.

Parse US and UK Dates in Python Without Guessing

PYTHON · US AND UK DATA · WORKED EXAMPLE

Parse US and UK Dates in Python Without Guessing

Turn source-specific CSV dates into clear reporting dates, while keeping ambiguous and invalid records visible.

What does 03/04/2026 mean?

The string alone cannot tell you. Under month/day/year it means March 4; under day/month/year it means April 3. Use the source system’s documented format, parse with that explicit format, and quarantine records whose format is unknown. Successful parsing is not proof that the intended date was chosen.

This synthetic example represents separate US and UK exports plus an ISO-style export. The labels describe this exercise’s source contracts, not a rule that every file from a country uses the same convention. European systems also vary. Confirm the contract for the specific dataset.

Why this matters in an analyst interview

Imagine combining sales activity from two regional systems. Both contain 03/04/2026. If you apply one format to the combined column, both rows may parse successfully while one lands in the wrong month. Monthly revenue and cohort assignments can then change without any missing-value warning.

The strongest answer starts with the source metadata, not a clever parser. Ask which system generated the export, what its date format is, and whether that format changed over time. Preserve the original text so a reviewer can trace a standardized date back to the input.

Run a complete example

This script uses Python’s standard library only. It reads five CSV rows, accepts three and rejects two. It makes no network calls and needs no package installation.

import csv
from datetime import datetime
from io import StringIO

raw = """id,source,date_text
1,us_export,03/04/2026
2,uk_export,03/04/2026
3,unknown,03/04/2026
4,uk_export,31/02/2026
5,iso_export,2026-09-23
"""
formats = {
    "us_export": "%m/%d/%Y",
    "uk_export": "%d/%m/%Y",
    "iso_export": "%Y-%m-%d",
}
accepted, rejected = [], []
for row in csv.DictReader(StringIO(raw)):
    fmt = formats.get(row["source"])
    if fmt is None:
        rejected.append((row["id"], "unknown source format"))
        continue
    try:
        parsed = datetime.strptime(row["date_text"], fmt).date()
    except ValueError:
        rejected.append((row["id"], "invalid date"))
        continue
    accepted.append((row["id"], parsed.isoformat()))

assert accepted == [
    ("1", "2026-03-04"),
    ("2", "2026-04-03"),
    ("5", "2026-09-23"),
]
assert rejected == [
    ("3", "unknown source format"),
    ("4", "invalid date"),
]
print("Accepted:", accepted)
print("Rejected:", rejected)

Verified result: row 1 becomes 2026-03-04; row 2 becomes 2026-04-03; row 5 remains 2026-09-23. Row 3 is rejected because its source format is unknown. Row 4 is rejected because February 31 is not a valid date.

Python’s datetime documentation defines the explicit parsing directives: %m is the month, %d the day and %Y the year with century. The CSV documentation explains DictReader, which exposes the input fields by column name.

Separate three different checks

Source meaning: do we know whether the first component is the day or month? This comes from an agreed source contract. Trying multiple formats in order does not resolve a string that fits more than one.

Calendar validity: does the supplied date exist? An explicit parser catches February 31 and invalid leap days. That is useful, but it cannot detect every semantic error. April 3 is a valid date even when the producer intended March 4.

Business validity: is the result plausible for this record? Compare an order date with its shipment date and the extraction window. Use those checks to flag contradictions for investigation, not to silently rewrite the source date.

Keep rejected rows in the workflow

The example returns a compact rejected list. In production, retain the source file identifier, row identifier, original value and reason in a controlled error output. Do not drop invalid dates and continue reporting without measuring how much data was excluded.

Reconcile input rows against accepted plus rejected rows: five equals three plus two here. If a source previously had no rejected dates and suddenly rejects half its rows, investigate an export-format change before labeling it a business trend. Avoid including unnecessary customer information in diagnostic logs.

For a monetary report, also reconcile the value associated with excluded rows. Two rejected orders can matter more than hundreds of accepted low-value orders. Keep known missing dates distinct from malformed dates so the remediation is appropriate.

Date format is not time zone

A calendar date such as 2026-09-23 contains no hour or time zone. Converting it into a different display format does not convert an event from London time to New York time. If the input is an event timestamp, preserve its time-zone information and decide the reporting zone before extracting the reporting date.

That is a separate problem from this parser. Use the daily active users and US time-zone example to practice timestamp boundaries. Do not attach midnight UTC to every date-only value unless the source definition explicitly requires it.

Test cases worth adding

  • 02/29/2024 in the US format should succeed; 02/29/2025 should fail.
  • An unknown source with a plausible date should still be rejected until its contract is known.
  • A blank date should follow a documented missing-value rule rather than becoming today’s date.
  • A timestamp supplied to a date-only field should be rejected or processed by a separate documented path.

The script validates the date’s meaning and calendar structure under the selected format. It does not enforce exact character width: Python may accept some unpadded components. If your contract requires exactly MM/DD/YYYY, add a lexical validation step before parsing and test it separately.

A concise interview explanation

“I would preserve the raw date and source, apply an explicit format per source contract, and separate unknown formats from invalid dates. I would reconcile accepted and rejected rows, then run business checks. I would not infer the meaning of an ambiguous string from the user’s location.”

Continue with Python interview practice, merge validation and SQL reconciliation. For coached preparation, review current interview plans and availability. All interview sessions and feedback are in English.

Leave a Reply

Discover more from Data Analyst Interview

Subscribe now to keep reading and get access to the full archive.

Continue reading

✉ WhatsApp