Skip to content

Commit 57ce67d

Browse files
dylanpulverSecrus
authored andcommitted
Fix diff_for_humans crashing for the zh locale
zh/custom.py used a NAMED placeholder in "after"/"before" ("{time}后", "{time}前") while DifferenceFormatter.format() substitutes positionally (difference_formatter.py:115,159 call locale.get(key).format(time)). So the two-datetime form raises KeyError: 'time' for every unit: a.diff_for_humans(b, locale="zh") -> KeyError: 'time' All 28 other locales use "{0}". zh is switched to match; no code change. The relative-to-now form was unaffected because it reads the CLDR translations table rather than these custom entries, and there was no tests/localization/test_zh.py at all, so nothing exercised this path. Adds that test file, covering the relative-to-now form and the two-datetime form that was crashing.
1 parent bd89085 commit 57ce67d

2 files changed

Lines changed: 47 additions & 2 deletions

File tree

src/pendulum/locales/zh/custom.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66

77
translations = {
88
# Relative time
9-
"after": "{time}后",
10-
"before": "{time}前",
9+
"after": "{0}后",
10+
"before": "{0}前",
1111
# Date formats
1212
"date_formats": {
1313
"LTS": "Ah点m分s秒",

tests/localization/test_zh.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from __future__ import annotations
2+
3+
import pendulum
4+
5+
6+
locale = "zh"
7+
8+
9+
def test_diff_for_humans():
10+
with pendulum.travel_to(pendulum.datetime(2016, 8, 29), freeze=True):
11+
diff_for_humans()
12+
13+
14+
def diff_for_humans():
15+
d = pendulum.now().subtract(seconds=1)
16+
assert d.diff_for_humans(locale=locale) == "1秒钟前"
17+
18+
d = pendulum.now().subtract(minutes=2)
19+
assert d.diff_for_humans(locale=locale) == "2分钟前"
20+
21+
d = pendulum.now().subtract(hours=2)
22+
assert d.diff_for_humans(locale=locale) == "2小时前"
23+
24+
d = pendulum.now().subtract(days=2)
25+
assert d.diff_for_humans(locale=locale) == "2天前"
26+
27+
d = pendulum.now().subtract(weeks=2)
28+
assert d.diff_for_humans(locale=locale) == "2周前"
29+
30+
d = pendulum.now().subtract(months=2)
31+
assert d.diff_for_humans(locale=locale) == "2个月前"
32+
33+
d = pendulum.now().subtract(years=2)
34+
assert d.diff_for_humans(locale=locale) == "2年前"
35+
36+
d = pendulum.now().add(seconds=1)
37+
assert d.diff_for_humans(locale=locale) == "1秒钟后"
38+
39+
d = pendulum.now().add(seconds=1)
40+
d2 = pendulum.now()
41+
assert d.diff_for_humans(d2, locale=locale) == "1秒钟后"
42+
assert d2.diff_for_humans(d, locale=locale) == "1秒钟前"
43+
44+
assert d.diff_for_humans(d2, True, locale=locale) == "1秒钟"
45+
assert d2.diff_for_humans(d.add(seconds=1), True, locale=locale) == "2秒钟"

0 commit comments

Comments
 (0)