Skip to content
Merged
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
10 changes: 10 additions & 0 deletions src/humanize/time.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,16 @@ def naturaldelta(
delta = dt.timedelta(seconds=value)
except (ValueError, TypeError):
return str(value)
except OverflowError:
# `int(value)` raises OverflowError for non-finite floats (inf/-inf),
# which, like NaN, are returned unchanged. A too-large *finite* value
# (whose OverflowError comes from `timedelta`) is still raised, per
# the documented `OverflowError` contract.
import math

if not math.isfinite(value):
Comment thread
hugovk marked this conversation as resolved.
return str(value)
raise

use_months = months

Expand Down
19 changes: 19 additions & 0 deletions tests/test_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,25 @@ def test_naturaldelta(test_input: float | dt.timedelta, expected: str) -> None:
assert humanize.naturaldelta(-test_input) == expected


@pytest.mark.parametrize(
"value, expected",
[
(float("nan"), "nan"),
(float("inf"), "inf"),
(float("-inf"), "-inf"),
],
)
def test_naturaldelta_non_finite(value: float, expected: str) -> None:
"""Non-finite floats are returned unchanged instead of raising."""
assert humanize.naturaldelta(value) == expected


def test_naturaldelta_too_large_value_raises() -> None:
"""A too-large *finite* value still raises OverflowError (unlike inf)."""
with pytest.raises(OverflowError):
humanize.naturaldelta(1e30)


@freeze_time(FROZEN_DATE)
@pytest.mark.parametrize(
"test_input, expected",
Expand Down