Skip to content

Commit

Permalink
Represent with a zero if the delta is too small
Browse files Browse the repository at this point in the history
If the delta is too small to be represented with the minimum unit,
represent it as "0 X" where X is the minimum unit.

Fixes #159
  • Loading branch information
eldipa committed Oct 19, 2020
1 parent 9d9de69 commit 62706fd
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/humanize/time.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,20 @@ def precisedelta(value, minimum_unit="seconds", suppress=(), format="%0.2f"):
>>> precisedelta(delta, suppress=['seconds', 'milliseconds', 'microseconds'])
'1.50 minutes'
```
If the delta is too small to be represented with the minimum unit,
a value of zero will be returned:
```pycon
>>> delta = dt.timedelta(seconds=1)
>>> precisedelta(delta, minimum_unit="minutes")
'0.02 minutes'
>>> delta = dt.timedelta(seconds=0.1)
>>> precisedelta(delta, minimum_unit="minutes")
'0 minutes'
```
"""
date, delta = date_and_delta(value)
Expand Down Expand Up @@ -501,7 +515,7 @@ def precisedelta(value, minimum_unit="seconds", suppress=(), format="%0.2f"):
texts = []
for unit, fmt in zip(reversed(Unit), fmts):
singular_txt, plural_txt, value = fmt
if value > 0:
if value > 0 or (not texts and unit == min_unit):
fmt_txt = ngettext(singular_txt, plural_txt, value)
if unit == min_unit and math.modf(value)[0] > 0:
fmt_txt = fmt_txt.replace("%d", format)
Expand Down
5 changes: 5 additions & 0 deletions tests/test_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,11 @@ def test_precisedelta_one_unit_enough(val, min_unit, expected):
"microseconds",
"1 year, 5 days and 2 seconds",
),
(
dt.timedelta(seconds=0.01),
"minutes",
"0 minutes",
),
],
)
def test_precisedelta_multiple_units(val, min_unit, expected):
Expand Down

0 comments on commit 62706fd

Please sign in to comment.