python-humanize / python-humanize/humanize

precisedelta() silently drops the sign of negative timedeltas

未关闭 适合新手
#379 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
Python
星标
756
派生
148
平均合并
6 天 1 小时
30 天内合并 PR
12

描述

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.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 precisedelta() 的实现及其现有的 docstring 和测试入手,然后运行提供的 negative-timedelta 复现,包括 minimum_unit="minutes" 的情况。为负值添加回归覆盖,并确认所选行为是一致的,同时保留现有的正值输出。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
backend
Issue 类型
缺陷
难度
2/5
预计耗时
1-3 小时
活跃度
活跃
描述清晰度
基本清楚
新手友好度
72/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。