python-humanize / python-humanize/humanize

precisedelta() silently drops the sign of negative timedeltas

Open Beginner friendly
#379 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
756
Forks
148
Avg merge
6d 1h
Merged PRs (30d)
12

Description

precisedelta() silently drops the sign of negative timedeltas — the output is byte-identical to the positive counterpart, so a negative delta rendered in any UI becomes indistinguishable from a positive one.

Version: humanize 4.16.0 / current master. Python 3.13.

Repro

import datetime as dt
from humanize import precisedelta

td = dt.timedelta(seconds=-3661)

print(precisedelta(td))                    # '1 hour, 1 minute and 1 second'
print(precisedelta(dt.timedelta(seconds=3661)))  # '1 hour, 1 minute and 1 second'  <- identical!

The sign is lost for every unit combination (also checked minimum_unit="minutes"). Neither the docstring nor the tests mention negative inputs at all, so it's unclear whether this is intended — but the current behavior makes the function unsafe for anything that can produce signed deltas (countdown corrections, progress deltas, A/B time differences), because the rendered string carries no trace of the direction.

For comparison, sibling function naturaldelta() also uses absolute value internally, but its output vocabulary ("a moment", "an hour") reads as inherently directionless; precisedelta's numeric output does not.

Suggested resolutions (either would work)

  1. Preserve the sign: prefix the result with - when value is negative (mirroring str(timedelta), which keeps the sign: str(td)'-1 day, 1:01:01').
  2. Or raise / document explicitly that only non-negative values are supported.

Option 1 seems most useful and backwards-compatible for positive inputs; option 2 at least removes the silent-corruption trap.

Happy to send a PR with either behavior + tests if maintainers indicate a preference.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the precisedelta() implementation and its existing docstring and tests, then run the provided negative-timedelta reproduction, including the minimum_unit="minutes" case. Add regression coverage for negative values and confirm the chosen behavior is consistent, while preserving the existing positive output.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
72/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.