Skip to content

precisedelta() erases the sign of negative timedeltas #534

Not planned

Description

@SonicHedghog

Summary

precisedelta() renders negative timedeltas byte-identically to positive ones — the sign is silently erased.

Reproduction (humanize 4.16.0)

import datetime, humanize

humanize.precisedelta(datetime.timedelta(seconds=-90))
# '1 minute and 30 seconds'

humanize.precisedelta(datetime.timedelta(seconds=+90))
# '1 minute and 30 seconds'   <-- byte-identical output for a different timedelta

humanize.precisedelta(datetime.timedelta(seconds=-3661))
# '1 hour, 1 minute and 1 second'   <-- no negative indication anywhere

Why this seems wrong

The docstring promises "a precise representation of a timedelta". Two different timedeltas (-90s and +90s) cannot have the same precise representation. The implementation applies abs() to the day/second components, so sign information is destroyed before formatting.

This matters in practice because negative timedeltas arise naturally from arithmetic — e.g. end - start with the operands accidentally swapped — and the sign erasure makes exactly that class of bug invisible in rendered output.

Possible resolutions

  • Prefix negative durations (e.g. '-1 minute and 30 seconds' or 'negative 1 minute...'); or
  • If negative timedeltas are intentionally out of domain, document that and/or raise rather than silently rendering a wrong positive duration.

The sibling function naturaldelta() has a related sign-erasure behavior; I filed that separately since the rendering path differs.

Activity

  1. SonicHedghog commented on Dec 2, 2026

    @SonicHedghog
    Author

    If a behavior change is welcome, I’d be happy to implement it with tests. If negative-timedelta normalization is intentional, I can instead prepare a narrow documentation clarification. I’ll wait for maintainer direction before opening a PR.

  2. SonicHedghog commented on Dec 2, 2026

    @SonicHedghog
    Author

    I re-checked both issues and PR history, and I missed substantial prior art: #173 deliberately normalized negative timedeltas with abs(), and #395/#412/#455 were later duplicate attempts to preserve the sign. Sorry for adding to that noise. I’m closing this and won’t pursue a behavior-change or further PR without maintainer invitation.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions