Skip to content

Fix td_format rendering negative durations as large positive ones - #72703

Closed
CaptainAni187 wants to merge 3 commits into
apache:mainfrom
CaptainAni187:fix/td-format-negative-durations
Closed

CaptainAni187 wants to merge 3 commits into
apache:mainfrom
CaptainAni187:fix/td-format-negative-durations

Conversation

@CaptainAni187

Copy link
Copy Markdown

Closes: #72694

td_format renders a negative duration as a large positive one:

td_format(timedelta(seconds=-3752))   # '29d:22h:57M:28s'
td_format(timedelta(days=-5))         # '25d'
td_format(-3752)                      # '<1s'

The last two lines are the same duration expressed two ways and they disagree.

Cause

The day-to-month conversion uses divmod, which floors:

months, delta.days = divmod(delta.days, 30)

so a relativedelta of days=-1 becomes months=-1, days=+29. _format_part skips any component below 1, which drops the -1 month that would have cancelled the +29 days and leaves the days behind.

The numeric branch differs because relativedelta(seconds=-3752) keeps a single negative seconds field instead of borrowing a day, so every component is dropped and the empty result falls through to <1s.

Change

Format the magnitude, then re-apply the sign. This keeps the existing output for non-negative durations untouched and makes the two input types agree:

td_format(timedelta(seconds=-3752))   # '-1h:2M:32s'
td_format(timedelta(days=-5))         # '-5d'
td_format(-3752)                      # '-1h:2M:32s'

A magnitude below one second still reads <1s regardless of sign, since prefixing a sign onto <1s would not tell the reader anything useful.

Tests

Adds test_td_format_negative alongside the existing test_td_format, covering both input types, the sub-second case, and the agreement between the two branches. It fails on main with '29d:22h:57M:28s' != '-1h:2M:32s'.

I also checked the sign invariant td_format(-x) == "-" + td_format(x) over 20,000 randomly generated durations for both input types, along with cross-type agreement — no violations. That sweep is not included in the test file, since the explicit cases cover the behaviour and are easier to read.

ruff check and ruff format are clean at the pinned 0.16.4, and the shared/timezones suite passes (31 passed).

`td_format` converted days to months with `divmod`, which floors, so a
relativedelta of days=-1 became months=-1, days=+29. `_format_part` then
dropped the negative month because it skips any component below 1, leaving
the 29 days behind. timedelta(seconds=-3752) rendered as '29d:22h:57M:28s'.

The numeric branch disagreed with the timedelta branch for the same
duration, since relativedelta(seconds=-3752) keeps a single negative
seconds field rather than borrowing a day, so every component was dropped
and the result fell through to '<1s'.

Format the magnitude and re-apply the sign, so a negative duration reads
as '-1h:2M:32s' and both input types agree.
@boring-cyborg

boring-cyborg Bot commented Sep 8, 2026

Copy link
Copy Markdown

Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our Contributors' Guide
Here are some useful points:

  • Pay attention to the quality of your code (ruff, mypy and type annotations). Our prek-hooks will help you with that.
  • In case of a new feature add useful documentation (in docstrings or in docs/ directory). Adding a new operator? Check this short guide Consider adding an example Dag that shows how users should use it.
  • Consider using Breeze environment for testing locally, it's a heavy docker but it ships with a working Airflow and a lot of integrations.
  • Be patient and persistent. It might take some time to get a review or get the final approval from Committers.
  • Please follow ASF Code of Conduct for all communication including (but not limited to) comments on Pull Requests, Mailing list and Slack.
  • Be sure to read the Airflow Coding style.
  • Always keep your Pull Requests rebased, otherwise your build might fail due to changes not related to your commits.
    Apache Airflow is a community-driven project and together we are making it better 🚀.
    In case of doubts contact the developers at:
    Mailing List: [email protected]
    Slack: https://s.apache.org/airflow-slack

@rjgoyln rjgoyln left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM overall! Two small readability points on the fix itself.
Just my thoughts — feel free to resolve them if you think otherwise.

Comment on lines +243 to +247
is_negative = td_object < dt.timedelta(0) if isinstance(td_object, dt.timedelta) else td_object < 0
if isinstance(td_object, dt.timedelta):
delta = relativedelta() + td_object
delta = relativedelta() + abs(td_object)
else:
delta = relativedelta(seconds=int(td_object))
delta = relativedelta(seconds=int(abs(td_object)))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ternary re-runs the isinstance check that the very next if performs. Folding the sign decision into the existing branch keeps one type dispatch instead of two:

Suggested change
is_negative = td_object < dt.timedelta(0) if isinstance(td_object, dt.timedelta) else td_object < 0
if isinstance(td_object, dt.timedelta):
delta = relativedelta() + td_object
delta = relativedelta() + abs(td_object)
else:
delta = relativedelta(seconds=int(td_object))
delta = relativedelta(seconds=int(abs(td_object)))
if isinstance(td_object, dt.timedelta):
is_negative = td_object < dt.timedelta(0)
delta = relativedelta() + abs(td_object)
else:
is_negative = td_object < 0
delta = relativedelta(seconds=int(abs(td_object)))

Comment on lines +234 to +235
A negative duration is formatted by magnitude and prefixed with `-`,
so timedelta(seconds=-3752) would become `-1h:2M:32s`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The sign rule has one exception that the docstring doesn't mention: a magnitude below one second still renders as an unsigned <1s, so td_format(-0.4) == td_format(0.4) == "<1s". That's a reasonable choice — and the PR description explains it — but a reader of the docstring alone would expect a - here.

Suggested change
A negative duration is formatted by magnitude and prefixed with `-`,
so timedelta(seconds=-3752) would become `-1h:2M:32s`.
A negative duration is formatted by magnitude and prefixed with `-`,
so timedelta(seconds=-3752) would become `-1h:2M:32s`. A magnitude below
one second is still `<1s`, without a sign.

Addresses review: the ternary repeated the isinstance check that the next
branch already performs. Also note the sub-second exception in the docstring,
where a magnitude below one second stays unsigned.
@CaptainAni187

Copy link
Copy Markdown
Author

Thanks @rjgoyln — both applied in 52db5de.

You were right that the ternary was doing the same isinstance dispatch the next branch performs; folding the sign decision into the two arms reads better and does one type check instead of two.

Good catch on the docstring too. The sub-second case was only explained in the PR description, which isn't much help to someone reading the function. It now says a magnitude below one second stays <1s without a sign.

shared/timezones: 31 passed. ruff check and ruff format clean.

@CaptainAni187

Copy link
Copy Markdown
Author

Closing — this was fixed on main by #72774 (commit 3e8f918) while this PR was open, so the conflict here is my change against an equivalent one that already landed.

Their approach negates up front with a prefix rather than my is_negative flag; same behaviour, including <1s staying unsigned for sub-second magnitudes. Their test covers the same cases too — both input types, days=-5, and the sub-second pair.

Thanks @rjgoyln for the review earlier; the readability points you raised were good ones and I'd applied both.

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.

td_format renders negative durations as large positive ones

2 participants