Skip to content

fix(time): precisedelta keeps the sign of negative timedeltas - #380

Open
Mukller wants to merge 3 commits into
python-humanize:mainfrom
Mukller:fix/precisedelta-negative-sign
Open

fix(time): precisedelta keeps the sign of negative timedeltas#380
Mukller wants to merge 3 commits into
python-humanize:mainfrom
Mukller:fix/precisedelta-negative-sign

Conversation

@Mukller

@Mukller Mukller commented Aug 24, 2026

Copy link
Copy Markdown

Fixes #379

precisedelta() silently dropped the sign of negative timedeltas: -3661 s
rendered byte-identical to +3661 s, making the function unsafe for signed
inputs.

Root cause

The sign was lost before precisedelta() even ran: the shared helper
_date_and_delta() returns _abs_timedelta(delta) (time.py), so every caller
receives the absolute value. precisedelta then decomposed already-positive
components.

Changes

  • precisedelta() captures the sign from the original value (timedelta
    comparison, datetime-vs-now comparison, or numeric < 0) and prefixes the
    rendered string with - for negative inputs. Zero stays unsigned.
  • Both return paths covered (single-unit and joined multi-unit).

Testing

Four new tests in tests/test_time.py: negative multi-unit, negative with a
coarser minimum_unit (float path), zero-stays-unsigned, positive-unchanged.
Full suite: 704 passed, 74 skipped.

Note: naturaldelta() shares the same helper, so it presumably also drops the
sign — left out of scope here to keep this PR focused, but worth a separate
issue if maintainers agree it's undesired there too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

precisedelta() silently drops the sign of negative timedeltas

1 participant