Skip to content

Commit db42e68

Browse files
committed
Account for missing ordinal categories in from_format candidates
Locales like Italian map only some plural categories (custom.ordinal has just 'other' -> '°'), so numbers in unmapped categories (8, 11, 80 use 'many') are formatted as plain digits by Locale.ordinalize(). from_format previously only accepted plain digits when the locale had no ordinal map at all, so parsing its own output raised ValueError. Always append a plain-digit fallback candidate alongside the suffixed forms so every ordinal token (Do, Mo, Qo, DDDo) accepts what format() emits. Add the Italian 'many' case from the review as a regression test. Co-authored-by: rahul05ranjan <11793455+rahul05ranjan@users.noreply.github.com>
1 parent 18012f1 commit db42e68

2 files changed

Lines changed: 19 additions & 6 deletions

File tree

‎src/pendulum/formatting/formatter.py‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,17 +48,15 @@
4848
def _ordinal_candidates(locale: Locale) -> tuple[str, ...]:
4949
"""Regex candidates matching an ordinal number in the given locale.
5050
51-
Mirrors ``Locale.ordinalize()``: locales without ordinal suffixes
52-
format ordinals as the plain number, so the parse pattern must
53-
accept plain digits for them.
51+
Mirrors ``Locale.ordinalize()``: locales whose ordinal map does not
52+
cover every plural category format those numbers as the plain
53+
number, so the parse pattern must accept plain digits as well.
5454
"""
5555
candidates = tuple(
5656
rf"\d+{o}" for o in (locale.get("custom.ordinal") or {}).values()
5757
)
58-
if not candidates:
59-
candidates = (r"\d+",)
6058

61-
return candidates
59+
return (*candidates, r"\d+")
6260

6361

6462
class Formatter:

‎tests/datetime/test_from_format.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,21 @@ def test_from_format_ordinal_month():
241241
assert_datetime(d, 1982, 6, 1, 0, 0, 0)
242242

243243

244+
def test_from_format_ordinal_with_partial_locale_ordinals():
245+
"""
246+
Locales whose ordinal map does not cover every plural category
247+
(Italian only maps ``other``; ``8`` falls in ``many``) format those
248+
numbers without a suffix; ``from_format`` must accept what
249+
``format`` emits.
250+
"""
251+
d = pendulum.datetime(1982, 8, 1)
252+
s = d.format("Mo YYYY", locale="it")
253+
assert s == "8 1982"
254+
255+
parsed = pendulum.from_format(s, "Mo YYYY", locale="it")
256+
assert_datetime(parsed, 1982, 8, 1, 0, 0, 0)
257+
258+
244259
def test_from_format_ordinal_quarter():
245260
d = pendulum.from_format("2nd 1982", "Qo YYYY")
246261
assert_datetime(d, 1982, 4, 1, 0, 0, 0)

0 commit comments

Comments
 (0)