Skip to content

Commit c2e6c6e

Browse files
authored
Encode support for the "fall back to short format" logic for time delta formatting (#1075)
Fixes #892
1 parent 1a03526 commit c2e6c6e

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

babel/dates.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -943,7 +943,14 @@ def _iter_patterns(a_unit):
943943
else:
944944
yield unit_rel_patterns['past']
945945
a_unit = f"duration-{a_unit}"
946-
yield locale._data['unit_patterns'].get(a_unit, {}).get(format)
946+
unit_pats = locale._data['unit_patterns'].get(a_unit, {})
947+
yield unit_pats.get(format)
948+
# We do not support `<alias>` tags at all while ingesting CLDR data,
949+
# so these aliases specified in `root.xml` are hard-coded here:
950+
# <unitLength type="long"><alias source="locale" path="../unitLength[@type='short']"/></unitLength>
951+
# <unitLength type="narrow"><alias source="locale" path="../unitLength[@type='short']"/></unitLength>
952+
if format in ("long", "narrow"):
953+
yield unit_pats.get("short")
947954

948955
for unit, secs_per_unit in TIMEDELTA_UNITS:
949956
value = abs(seconds) / secs_per_unit
@@ -956,7 +963,8 @@ def _iter_patterns(a_unit):
956963
for patterns in _iter_patterns(unit):
957964
if patterns is not None:
958965
pattern = patterns.get(plural_form) or patterns.get('other')
959-
break
966+
if pattern:
967+
break
960968
# This really should not happen
961969
if pattern is None:
962970
return ''

tests/test_dates.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -742,3 +742,12 @@ def test_en_gb_first_weekday():
742742

743743
def test_issue_798():
744744
assert dates.format_timedelta(timedelta(), format='narrow', locale='es_US') == '0s'
745+
746+
747+
def test_issue_892():
748+
assert dates.format_timedelta(timedelta(seconds=1), format='narrow', locale='pt_BR') == '1 s'
749+
assert dates.format_timedelta(timedelta(minutes=1), format='narrow', locale='pt_BR') == '1 min'
750+
assert dates.format_timedelta(timedelta(hours=1), format='narrow', locale='pt_BR') == '1 h'
751+
assert dates.format_timedelta(timedelta(days=1), format='narrow', locale='pt_BR') == '1 dia'
752+
assert dates.format_timedelta(timedelta(days=30), format='narrow', locale='pt_BR') == '1 mês'
753+
assert dates.format_timedelta(timedelta(days=365), format='narrow', locale='pt_BR') == '1 ano'

0 commit comments

Comments
 (0)