Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/allotropy/parsers/utils/timestamp_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def _should_use_day_first(time_str: str, locale_str: str | None) -> bool:
if re.match(r"^\d{4}[-/.]", time_str):
return False

# Use locale data for non-ISO formats
# No locale specified: default to American format for backward compatibility
if not locale_str:
return False

Expand All @@ -60,7 +60,9 @@ def _should_use_day_first(time_str: str, locale_str: str | None) -> bool:

return False
except Exception:
return False
# Invalid/unknown locale: default to day-first since most of the world uses it
# Only en_US and a few other locales use month-first (MM/DD/YYYY)
return True


class TimestampParser:
Expand Down
23 changes: 20 additions & 3 deletions tests/parsers/utils/timestamp_parser_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,11 @@ def test_none_locale_returns_false(self) -> None:
assert _should_use_day_first("01/15/2023", None) is False
assert _should_use_day_first("15/01/2023", None) is False

def test_invalid_locale_returns_false(self) -> None:
# Invalid locales default to False
assert _should_use_day_first("01/15/2023", "invalid_LOCALE") is False
def test_invalid_locale_returns_true(self) -> None:
# Invalid/unknown locales default to day-first since most of world uses it
assert _should_use_day_first("01/15/2023", "invalid_LOCALE") is True
assert _should_use_day_first("15/01/2023", "xyz_ABC") is True
assert _should_use_day_first("01/02/2023", "not_a_real_locale") is True


class TestTimestampParser:
Expand Down Expand Up @@ -142,6 +144,21 @@ def test_parse_invalid_date_raises_error(self) -> None:
):
parser.parse("not a date")

def test_invalid_locale_defaults_to_day_first(self) -> None:
"""Invalid/unknown locales should default to day-first (most common globally)."""
parser = TimestampParser()

# With an invalid locale, ambiguous dates should parse as day-first
# 01/02/2023 should be February 1st (day-first), not January 2nd
with set_locale_context("invalid_LOCALE"):
result = parser.parse("01/02/2023")
assert "2023-02-01" in result, "Invalid locale should default to day-first"

# Another invalid locale - should still use day-first
with set_locale_context("xyz_ABC"):
result = parser.parse("15/01/2023")
assert "2023-01-15" in result, "Unknown locale should default to day-first"

def test_real_world_examples(self) -> None:
"""Test real-world date formats from various instruments."""
parser = TimestampParser()
Expand Down
Loading