Skip to content

Fix get_timezone_gmt hour for negative fractional offsets - #1291

Open
vineethsaivs wants to merge 2 commits into
python-babel:masterfrom
vineethsaivs:fix/timezone-gmt-negative-offset
Open

Fix get_timezone_gmt hour for negative fractional offsets#1291
vineethsaivs wants to merge 2 commits into
python-babel:masterfrom
vineethsaivs:fix/timezone-gmt-negative-offset

Conversation

@vineethsaivs

Copy link
Copy Markdown

Summary

get_timezone_gmt renders the wrong hour for any timezone whose UTC offset has a non-zero minute part and is negative. For example, Newfoundland Standard Time (America/St_Johns, UTC-03:30):

>>> from datetime import datetime
>>> from babel.dates import get_timezone, get_timezone_gmt
>>> tz = get_timezone('America/St_Johns')
>>> dt = datetime(2007, 1, 1, 12, 0, tzinfo=tz)
>>> get_timezone_gmt(dt, locale='en')
'GMT-04:30'          # should be 'GMT-03:30'
>>> get_timezone_gmt(dt, 'short', locale='en')
'-0430'              # should be '-0330'

Pacific/Marquesas (UTC-09:30) is likewise rendered as GMT-10:30. Positive fractional offsets (Asia/Kolkata, +05:30) and whole-hour negatives (America/Los_Angeles, -08:00) are correct, so this is specific to negative offsets with minutes. Newfoundland Time covers a real, populated region, so this is user-facing incorrect output.

Root cause

divmod() on a negative value floors the quotient and returns a non-negative remainder:

>>> divmod(-12600, 3600)   # -3:30 in seconds
(-4, 1800)

The code printed the floored hour (-4) via %+03d while taking the minutes from the positive remainder (1800 // 60 == 30), producing -04:30 for a -03:30 offset.

Fix

Decompose the offset from its absolute value and track the sign separately (the same idiom the code already uses elsewhere):

sign = '-' if seconds < 0 else '+'
hours, seconds = divmod(abs(seconds), 3600)

and emit the sign explicitly ('%s%02d...') instead of relying on '%+03d'.

For every offset that already formatted correctly the output is unchanged: '%s%02d' with the explicit sign is byte-identical to '%+03d' whenever 0 <= hours < 100. I verified this exhaustively across all offsets from -12:00 to +14:00 in 15-minute steps and all four widths (plus return_z): the new code differs from the old in exactly the negative-fractional cases and nowhere else.

Tests

Added three assertions to the existing test_get_timezone_gmt (already parametrized over both the pytz and zoneinfo backends). They fail before the change (AssertionError: assert 'GMT-04:30' == 'GMT-03:30') and pass after, on both backends.

Happy to add a CHANGES.rst bugfix entry if you would like one included in this PR rather than compiled at release time.

For a timezone whose UTC offset has a non-zero minute part and is
negative (for example America/St_Johns at UTC-03:30), get_timezone_gmt
rendered the hour one step too far from zero, producing 'GMT-04:30'
instead of 'GMT-03:30'.

divmod() on a negative number floors the quotient and returns a
non-negative remainder, so divmod(-12600, 3600) is (-4, 1800): the code
printed the floored hour -4 while taking the minutes from the positive
remainder. Decompose the offset from its absolute value and track the
sign separately. For every offset that already formatted correctly the
output is unchanged, because '%s%02d' with the explicit sign matches
'%+03d' whenever 0 <= hours < 100.
@codecov

codecov Bot commented Jul 30, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.23%. Comparing base (baf9431) to head (8cef79c).
⚠️ Report is 16 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1291      +/-   ##
==========================================
+ Coverage   92.05%   92.23%   +0.17%     
==========================================
  Files          27       27              
  Lines        4720     4762      +42     
==========================================
+ Hits         4345     4392      +47     
+ Misses        375      370       -5     
Flag Coverage Δ
macos-14-3.10 91.28% <100.00%> (+0.18%) ⬆️
macos-14-3.11 91.22% <100.00%> (+0.18%) ⬆️
macos-14-3.12 91.43% <100.00%> (+0.18%) ⬆️
macos-14-3.13 91.43% <100.00%> (+0.18%) ⬆️
macos-14-3.14 91.41% <100.00%> (+0.18%) ⬆️
macos-14-3.15 91.41% <100.00%> (?)
macos-14-3.8 91.15% <100.00%> (+0.18%) ⬆️
macos-14-3.9 91.21% <100.00%> (+0.18%) ⬆️
macos-14-pypy3.10 91.28% <100.00%> (+0.18%) ⬆️
ubuntu-24.04-3.10 91.30% <100.00%> (+0.18%) ⬆️
ubuntu-24.04-3.11 91.24% <100.00%> (+0.18%) ⬆️
ubuntu-24.04-3.12 91.45% <100.00%> (+0.18%) ⬆️
ubuntu-24.04-3.13 91.45% <100.00%> (+0.18%) ⬆️
ubuntu-24.04-3.14 91.43% <100.00%> (+0.18%) ⬆️
ubuntu-24.04-3.15 91.43% <100.00%> (?)
ubuntu-24.04-3.8 91.17% <100.00%> (+0.18%) ⬆️
ubuntu-24.04-3.9 91.23% <100.00%> (+0.18%) ⬆️
ubuntu-24.04-pypy3.10 91.30% <100.00%> (+0.18%) ⬆️
windows-2022-3.10 91.29% <100.00%> (+0.18%) ⬆️
windows-2022-3.11 91.23% <100.00%> (+0.18%) ⬆️
windows-2022-3.12 91.44% <100.00%> (+0.18%) ⬆️
windows-2022-3.13 91.44% <100.00%> (+0.18%) ⬆️
windows-2022-3.14 91.42% <100.00%> (+0.18%) ⬆️
windows-2022-3.15 91.42% <100.00%> (?)
windows-2022-3.8 91.27% <100.00%> (+0.18%) ⬆️
windows-2022-3.9 91.22% <100.00%> (+0.18%) ⬆️
windows-2022-pypy3.10 91.29% <100.00%> (+0.18%) ⬆️

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.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@akx akx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

One small change request so we do a little less work for the Z case.

Comment thread babel/dates.py Outdated
Comment on lines 464 to 467
sign = '-' if seconds < 0 else '+'
hours, seconds = divmod(abs(seconds), 3600)
if return_z and hours == 0 and seconds == 0:
return 'Z'

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

While we're at it, let's move this check higher up, before we do the sign and divmod dance:

Suggested change
sign = '-' if seconds < 0 else '+'
hours, seconds = divmod(abs(seconds), 3600)
if return_z and hours == 0 and seconds == 0:
return 'Z'
if return_z and seconds == 0:
return 'Z'
sign = '-' if seconds < 0 else '+'
hours, seconds = divmod(abs(seconds), 3600)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done in the latest commit, exactly as suggested.

Checked the two orderings are equivalent rather than eyeballing it: before the divmod, seconds is the whole offset, and after it hours == 0 and seconds == 0 is true only when that whole offset was zero, so the condition is the same one. Compared old against new over every 15-minute offset in +/-18h plus every single second in +/-2h, across all four widths and both return_z values: 116368 combinations, 0 differences.

Thanks for the zone_formats["gmt"] census too, that answers the question I had about whether any locale puts the offset first in a way that would interact with the iso8601_short early return. '%s GMT' and the other four leading-%s formats never reach that branch anyway, since it only fires for iso8601_short, which does not use zone_formats.

Comment thread babel/dates.py
else:
pattern = locale.zone_formats['gmt'] % '%+03d:%02d'
return pattern % (hours, seconds // 60)
pattern = locale.zone_formats['gmt'] % '%s%02d:%02d'

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Just for my own record: over all of the locales we have now, zone_formats["gmt"]s are

Counter({'GMT%s': 937, 'UTC%s': 53, 'غرينتش%s': 29, 'GMT %s': 25, '𞤑𞤖𞤘%s': 13, 'जीएमटी%s': 4, '%s GMT': 4, 'MAG%s': 3, 'ᱡᱤᱮᱢᱴᱤ%s': 3, 'WAT%s': 3, '%s گرینویچ': 3, 'জি এম টি %s': 3, 'گرینیچ %s': 3, 'TMG%s': 2, 'जी.एम.टी. %s': 2, '𐐘𐐣𐐓 %s': 2, '%s Gk': 2, 'ម៉ោង\u200bសកល %s': 2, '[GMT]%s': 2, 'ग्री॰ मै॰ टै॰%s': 2, '·𐑜𐑥𐑑%s': 2, 'Гринуич%s': 2, 'जि.एम.ति %s': 2, 'ꋧꃅꎕꏦꄮꈉ%s': 2, 'ߜ߭ߕߖ%s': 2, 'जी एम टी %s': 2, 'tenpo UTC%s': 2, 'ཇི་ཨེམ་ཏི་%s': 2, 'ጂ ኤም ቲ%s': 2, 'GMT%s\u200e': 2, 'ග්\u200dරිමවේ%s': 2, 'ജിഎംടി %s': 2})

so this'll work as before.

Per review: the zero-offset early return does not need the sign or the
divmod, so hoist it above them. `seconds == 0` before the divmod is the same
condition as `hours == 0 and seconds == 0` after it, since divmod splits the
same total.
@codspeed-hq

codspeed-hq Bot commented Jul 31, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 88 untouched benchmarks


Comparing vineethsaivs:fix/timezone-gmt-negative-offset (8cef79c) with master (c2fdae6)

Open in CodSpeed

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.

2 participants