Skip to content

Commit

Permalink
Support short and narrow formats for format_timedelta(..., add_direct…
Browse files Browse the repository at this point in the history
…ion=True) (#1163)

Fixes #1162
  • Loading branch information
akx authored Jan 8, 2025
1 parent fb8dbba commit 6bbdc0e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
8 changes: 6 additions & 2 deletions babel/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -940,16 +940,20 @@ def format_timedelta(
else:
seconds = delta
locale = Locale.parse(locale)
date_fields = locale._data["date_fields"]
unit_patterns = locale._data["unit_patterns"]

def _iter_patterns(a_unit):
if add_direction:
unit_rel_patterns = locale._data['date_fields'][a_unit]
# Try to find the length variant version first ("year-narrow")
# before falling back to the default.
unit_rel_patterns = (date_fields.get(f"{a_unit}-{format}") or date_fields[a_unit])
if seconds >= 0:
yield unit_rel_patterns['future']
else:
yield unit_rel_patterns['past']
a_unit = f"duration-{a_unit}"
unit_pats = locale._data['unit_patterns'].get(a_unit, {})
unit_pats = 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:
Expand Down
21 changes: 21 additions & 0 deletions tests/test_dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -807,3 +807,24 @@ def test_issue_892():
def test_issue_1089():
assert dates.format_datetime(datetime.now(), locale="ja_JP@mod")
assert dates.format_datetime(datetime.now(), locale=Locale.parse("ja_JP@mod"))


@pytest.mark.parametrize(('locale', 'format', 'negative', 'expected'), [
('en_US', 'long', False, 'in 3 hours'),
('en_US', 'long', True, '3 hours ago'),
('en_US', 'narrow', False, 'in 3h'),
('en_US', 'narrow', True, '3h ago'),
('en_US', 'short', False, 'in 3 hr.'),
('en_US', 'short', True, '3 hr. ago'),
('fi_FI', 'long', False, '3 tunnin päästä'),
('fi_FI', 'long', True, '3 tuntia sitten'),
('fi_FI', 'short', False, '3 t päästä'),
('fi_FI', 'short', True, '3 t sitten'),
('sv_SE', 'long', False, 'om 3 timmar'),
('sv_SE', 'long', True, 'för 3 timmar sedan'),
('sv_SE', 'short', False, 'om 3 tim'),
('sv_SE', 'short', True, 'för 3 tim sedan'),
])
def test_issue_1162(locale, format, negative, expected):
delta = timedelta(seconds=10800) * (-1 if negative else +1)
assert dates.format_timedelta(delta, add_direction=True, format=format, locale=locale) == expected

0 comments on commit 6bbdc0e

Please sign in to comment.