Skip to content

fix: preserve negative UTC offsets in LocalTimezone.fromutc - #10519

Merged
auvipy merged 3 commits into
celery:mainfrom
waterWang:fix-negative-timezone-offset
Aug 26, 2026
Merged

auvipy merged 3 commits into
celery:mainfrom
waterWang:fix-negative-timezone-offset

Conversation

@waterWang

Copy link
Copy Markdown
Contributor

What

Fixes #10517 — LocalTimezone.fromutc() computes the UTC offset from timedelta.seconds, which is always normalized to [0, 86399) with the sign carried by timedelta.days. For any locale with a negative UTC offset (whole western hemisphere), the computed offset flips sign and inflates up to +23:59, corrupting every UTC→local conversion by up to ~24 hours.

Root cause

For a -04:00 zone, utcoffset(dt) returns timedelta(days=-1, seconds=72000); dividing .seconds by 60 yields +1200 minutes instead of -240, so datetime.timezone(timedelta(minutes=1200)) is a +20:00 zone.

Fix

offset = int(self.utcoffset(dt).total_seconds() // 60)

Uses the full signed value. Adds a regression test pinning the US-Eastern DST case (-04:00).

Impact

Silent schedule skew across western-hemisphere deployments running with enable_utc=False, and any environment where the tzlocal fallback engages (bare containers, missing /etc/localtime).

…lery#10517)

`timedelta.seconds` is normalized to [0, 86399] with the sign
carried by `timedelta.days`, so the old code turned a -04:00
offset into +20:00 for any western-hemisphere (negative offset)
locale, corrupting every UTC->local conversion by up to ~24h
when `enable_utc=False` (or the tzlocal fallback engages).

Use the full signed value from `total_seconds()` instead, and add
a regression test pinning the -04:00 US-Eastern DST case.
@auvipy
auvipy requested review from auvipy and a lite review from Copilot August 26, 2026 14:05

Copilot AI 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.

Pull request overview

Fixes an incorrect UTC→local conversion in celery.utils.time.LocalTimezone.fromutc() for negative-offset locales by computing the offset from the signed timedelta.total_seconds() instead of the normalized .seconds field. This prevents western-hemisphere deployments (and tzlocal-fallback environments) from silently converting offsets like -04:00 into large positive offsets such as +20:00.

Changes:

  • Compute UTC offset minutes using self.utcoffset(dt).total_seconds() to preserve the sign for negative offsets.
  • Add a regression test that simulates a US-Eastern DST scenario and asserts the resulting local time and utcoffset() are correct.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
celery/utils/time.py Fixes LocalTimezone.fromutc() offset calculation to preserve negative UTC offsets.
t/unit/utils/test_time.py Adds a regression test covering negative-offset (DST) UTC→local conversion.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@codecov

codecov Bot commented Aug 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.75%. Comparing base (7c846b6) to head (e92cb23).

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #10519      +/-   ##
==========================================
+ Coverage   88.72%   88.75%   +0.03%     
==========================================
  Files         153      153              
  Lines       19938    19938              
  Branches     2331     2331              
==========================================
+ Hits        17689    17695       +6     
+ Misses       1951     1945       -6     
  Partials      298      298              
Flag Coverage Δ
unittests 88.72% <100.00%> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

@auvipy auvipy added this to the 5.7.0 milestone Aug 26, 2026
@auvipy
auvipy merged commit 856df3c into celery:main Aug 26, 2026
356 of 358 checks passed
auvipy added a commit that referenced this pull request Sep 18, 2026
* Truncate utcoffset() toward zero instead of floor-dividing

time.timezone/time.altzone are seconds west of UTC. utcoffset()
converted them to whole hours with `// 3600`, which floor-divides:
for a fractional-hour, east-of-UTC zone (India/Sri Lanka/Iran at
UTC+5:30, seconds = -19800), this rounds the magnitude up
(-19800 // 3600 == -6) instead of truncating to the correct -5.
West-of-UTC fractional offsets are unaffected, since floor and
truncation agree for positive dividends -- this is a sign asymmetry,
not a general precision limitation.

utcoffset() feeds events/dispatcher.py (attached to every worker
event) and events/receiver.py's adjust_timestamp() (cross-timezone
event timestamp correction), so a worker in one of these locales
skews its reported offset by a full hour.

Different bug from LocalTimezone.fromutc() (#10517/#10519), which
lost the sign entirely via timedelta.seconds; this one only
mis-rounds the magnitude for fractional hours via `//`.
LocalTimezone.__repr__ a few lines above already truncates the
equivalent seconds-to-hours conversion -- this matches that existing
pattern instead of floor-dividing.

Added regression tests pinning both the fractional-hour case and
confirming whole-hour zones are unaffected.

* Return the exact fractional utcoffset() instead of rounding it

Review on the previous commit (truncate instead of floor) showed
truncation is not actually a fix: for a :30 zone like India it is
30 minutes off, same as floor, just in the other direction, and for
a :45 zone (Nepal +5:45, Chatham/Eucla +8:45) truncation is 45
minutes off versus floor's 15 -- strictly worse, not better.

The rounding itself was never needed. utcoffset()'s only consumer,
adjust_timestamp(), does plain float arithmetic, and the value's
only other use is passed through the event dict in
events/dispatcher.py and read back via itemgetter in
events/receiver.py -- nothing requires an int. Returning
time.timezone/altzone / 3600 directly (no floor, no truncation) is
exact for every zone, fractional or whole-hour alike.

adjust_timestamp()'s offset parameter is widened from int to float
to match, since it now receives fractional values.

Tests updated: the India case now asserts the exact -5.5 instead of
pinning the previously-"fixed" but still-wrong -5, and a new test
covers a :45 zone (Nepal, -5.75), which is where floor and
truncation actually diverge in how wrong they are.

---------

Co-authored-by: Asif Saif Uddin {"Auvi":"অভি"} <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

LocalTimezone.fromutc corrupts offsets for negative-UTC-offset locales (timedelta.seconds discards sign)

3 participants