Skip to content

Commit 809e66b

Browse files
authored
Merge pull request #170 from eldipa/Issue-159-Represent-as-Zero-a-Too-Small-Value
Represent with a zero if the delta is too small
2 parents 9d9de69 + 62706fd commit 809e66b

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

src/humanize/time.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,20 @@ def precisedelta(value, minimum_unit="seconds", suppress=(), format="%0.2f"):
426426
>>> precisedelta(delta, suppress=['seconds', 'milliseconds', 'microseconds'])
427427
'1.50 minutes'
428428
429+
```
430+
431+
If the delta is too small to be represented with the minimum unit,
432+
a value of zero will be returned:
433+
434+
```pycon
435+
>>> delta = dt.timedelta(seconds=1)
436+
>>> precisedelta(delta, minimum_unit="minutes")
437+
'0.02 minutes'
438+
439+
>>> delta = dt.timedelta(seconds=0.1)
440+
>>> precisedelta(delta, minimum_unit="minutes")
441+
'0 minutes'
442+
429443
```
430444
"""
431445
date, delta = date_and_delta(value)
@@ -501,7 +515,7 @@ def precisedelta(value, minimum_unit="seconds", suppress=(), format="%0.2f"):
501515
texts = []
502516
for unit, fmt in zip(reversed(Unit), fmts):
503517
singular_txt, plural_txt, value = fmt
504-
if value > 0:
518+
if value > 0 or (not texts and unit == min_unit):
505519
fmt_txt = ngettext(singular_txt, plural_txt, value)
506520
if unit == min_unit and math.modf(value)[0] > 0:
507521
fmt_txt = fmt_txt.replace("%d", format)

tests/test_time.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -496,6 +496,11 @@ def test_precisedelta_one_unit_enough(val, min_unit, expected):
496496
"microseconds",
497497
"1 year, 5 days and 2 seconds",
498498
),
499+
(
500+
dt.timedelta(seconds=0.01),
501+
"minutes",
502+
"0 minutes",
503+
),
499504
],
500505
)
501506
def test_precisedelta_multiple_units(val, min_unit, expected):

0 commit comments

Comments
 (0)