Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix naturaldelta sub second precision #169

Merged
Merged
Show file tree
Hide file tree
Changes from 4 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
6 changes: 4 additions & 2 deletions src/humanize/time.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@ def naturaldelta(
Returns:
str (str or `value`): A natural representation of the amount of time
elapsed unless `value` is not datetime.timedelta or cannot be
converted to int. In that case, a `value` is returned unchanged.
converted to int (cannot be float due to 'inf' or 'nan).
hugovk marked this conversation as resolved.
Show resolved Hide resolved
In that case, a `value` is returned unchanged.

Raises:
OverflowError: If `value` is too large to convert to datetime.timedelta.
Expand All @@ -131,7 +132,8 @@ def naturaldelta(
delta = value
else:
try:
value = int(value)
int(value) # Explicitly don't support string such as "NaN" or "inf"
value = float(value)
delta = dt.timedelta(seconds=value)
except (ValueError, TypeError):
return str(value)
Expand Down
3 changes: 2 additions & 1 deletion tests/test_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def test_naturaldelta_nomonths(test_input: dt.timedelta, expected: str) -> None:
(dt.timedelta(days=999_999_999), "2,739,726 years"),
],
)
def test_naturaldelta(test_input: int | dt.timedelta, expected: str) -> None:
def test_naturaldelta(test_input: float | dt.timedelta, expected: str) -> None:
assert humanize.naturaldelta(test_input) == expected


Expand Down Expand Up @@ -339,6 +339,7 @@ def test_naturaldelta_minimum_unit_explicit(

# Act / Assert
assert humanize.naturaldelta(delta, minimum_unit=minimum_unit) == expected
assert humanize.naturaldelta(seconds, minimum_unit=minimum_unit) == expected


@freeze_time("2020-02-02")
Expand Down
Loading