Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions src/humanize/time.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

from __future__ import annotations

import datetime

__lazy_modules__ = {"humanize.i18n", "humanize.number"}

from enum import Enum
Expand Down Expand Up @@ -546,6 +548,13 @@ def precisedelta(

```
"""
if isinstance(value, datetime.timedelta):
negative = value < datetime.timedelta(0)
elif isinstance(value, (int, float)):
negative = value < 0
else:
negative = False

date, delta = _date_and_delta(value, precise=True)
if date is None:
return str(value)
Expand Down Expand Up @@ -673,12 +682,13 @@ def precisedelta(
break

if len(texts) == 1:
return texts[0]

head = ", ".join(texts[:-1])
tail = texts[-1]
result = texts[0]
else:
head = ", ".join(texts[:-1])
tail = texts[-1]
result = _("%s and %s") % (head, tail)

return _("%s and %s") % (head, tail)
return f"-{result}" if negative else result


def _rounding_by_fmt(format: str, value: float) -> float | int:
Expand Down
17 changes: 17 additions & 0 deletions tests/test_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -837,6 +837,23 @@ def test_precisedelta_suppress_units(
def test_precisedelta_bogus_call() -> None:
assert humanize.precisedelta(None) == "None"


def test_precisedelta_negative() -> None:
# regression: negative timedeltas must keep their sign
# https://github.com/python-humanize/humanize/issues/379
assert (
humanize.precisedelta(dt.timedelta(seconds=-3661))
== "-1 hour, 1 minute and 1 second"
)
assert (
humanize.precisedelta(dt.timedelta(seconds=3661))
== "1 hour, 1 minute and 1 second"
)
assert (
humanize.precisedelta(dt.timedelta(seconds=-3661), minimum_unit="minutes")
== "-1 hour and 1.02 minutes"
)

with pytest.raises(
ValueError,
match="Minimum unit is suppressed and no suitable replacement was found",
Expand Down