Skip to content

Commit

Permalink
Encode support for the "fall back to short format" logic for time del…
Browse files Browse the repository at this point in the history
…ta formatting (#1075)

Fixes #892
  • Loading branch information
akx committed Apr 25, 2024
1 parent 1a03526 commit c2e6c6e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
12 changes: 10 additions & 2 deletions babel/dates.py
Expand Up @@ -943,7 +943,14 @@ def _iter_patterns(a_unit):
else:
yield unit_rel_patterns['past']
a_unit = f"duration-{a_unit}"
yield locale._data['unit_patterns'].get(a_unit, {}).get(format)
unit_pats = locale._data['unit_patterns'].get(a_unit, {})
yield unit_pats.get(format)
# We do not support `<alias>` tags at all while ingesting CLDR data,
# so these aliases specified in `root.xml` are hard-coded here:
# <unitLength type="long"><alias source="locale" path="../unitLength[@type='short']"/></unitLength>
# <unitLength type="narrow"><alias source="locale" path="../unitLength[@type='short']"/></unitLength>
if format in ("long", "narrow"):
yield unit_pats.get("short")

for unit, secs_per_unit in TIMEDELTA_UNITS:
value = abs(seconds) / secs_per_unit
Expand All @@ -956,7 +963,8 @@ def _iter_patterns(a_unit):
for patterns in _iter_patterns(unit):
if patterns is not None:
pattern = patterns.get(plural_form) or patterns.get('other')
break
if pattern:
break
# This really should not happen
if pattern is None:
return ''
Expand Down
9 changes: 9 additions & 0 deletions tests/test_dates.py
Expand Up @@ -742,3 +742,12 @@ def test_en_gb_first_weekday():

def test_issue_798():
assert dates.format_timedelta(timedelta(), format='narrow', locale='es_US') == '0s'


def test_issue_892():
assert dates.format_timedelta(timedelta(seconds=1), format='narrow', locale='pt_BR') == '1 s'
assert dates.format_timedelta(timedelta(minutes=1), format='narrow', locale='pt_BR') == '1 min'
assert dates.format_timedelta(timedelta(hours=1), format='narrow', locale='pt_BR') == '1 h'
assert dates.format_timedelta(timedelta(days=1), format='narrow', locale='pt_BR') == '1 dia'
assert dates.format_timedelta(timedelta(days=30), format='narrow', locale='pt_BR') == '1 mês'
assert dates.format_timedelta(timedelta(days=365), format='narrow', locale='pt_BR') == '1 ano'

0 comments on commit c2e6c6e

Please sign in to comment.