Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Encode support for the "fall back to short format" logic for time delta formatting #1075

Merged
merged 1 commit into from Apr 25, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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'