From ae7afad9f39844b05f00257c316b6cd377e93294 Mon Sep 17 00:00:00 2001 From: Tomas Roun Date: Mon, 9 Nov 2026 15:59:31 +0100 Subject: [PATCH] Display seconds in GMT offsets if available --- babel/dates.py | 13 +++++++++---- tests/test_dates.py | 15 ++++++++++++++- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/babel/dates.py b/babel/dates.py index 6f810c1d5..449248223 100644 --- a/babel/dates.py +++ b/babel/dates.py @@ -529,16 +529,21 @@ def get_timezone_gmt( if return_z and seconds == 0: return 'Z' sign = '-' if seconds < 0 else '+' - hours, seconds = divmod(abs(seconds), 3600) - if seconds == 0 and width == 'iso8601_short': + hours, remainder = divmod(abs(seconds), 3600) + minutes, seconds = divmod(remainder, 60) + if remainder == 0 and width == 'iso8601_short': return '%s%02d' % (sign, hours) elif width == 'short' or width == 'iso8601_short': pattern = '%s%02d%02d' elif width == 'iso8601': pattern = '%s%02d:%02d' else: - pattern = locale.zone_formats['gmt_utc' if utc else 'gmt'] % '%s%02d:%02d' - return pattern % (sign, hours, seconds // 60) + # The long format shows seconds if the zone offset has any + long_offset = f'{sign}{hours:02d}:{minutes:02d}' + if seconds: + long_offset += f':{seconds:02d}' + return locale.zone_formats['gmt_utc' if utc else 'gmt'] % long_offset + return pattern % (sign, hours, minutes) def get_timezone_location( diff --git a/tests/test_dates.py b/tests/test_dates.py index 76a002bc3..e1b31875d 100644 --- a/tests/test_dates.py +++ b/tests/test_dates.py @@ -11,7 +11,7 @@ # history and logs, available at https://github.com/python-babel/babel/commits/master/. import calendar -from datetime import date, datetime, time, timedelta +from datetime import date, datetime, time, timedelta, timezone import freezegun import pytest @@ -320,6 +320,19 @@ def test_get_timezone_gmt_utc(timezone_getter, locale, gmt, utc): assert dates.get_timezone_gmt(dt, 'short', locale=locale, utc=True) == '-0330' +@pytest.mark.parametrize(('offset', 'expected'), [ + (timedelta(hours=1, minutes=30, seconds=15), 'GMT+01:30:15'), + (timedelta(hours=-0, minutes=-44, seconds=-30), 'GMT-00:44:30'), + (timedelta(hours=2, seconds=5), 'GMT+02:00:05'), + (timedelta(hours=2), 'GMT+02:00'), + (timedelta(0), 'GMT+00:00'), +]) +def test_get_timezone_gmt_seconds(offset, expected): + # The long localized GMT format should display seconds if any + dt = datetime(2007, 1, 1, tzinfo=timezone(offset)) + assert dates.get_timezone_gmt(dt, width='long', locale='en') == expected + + def test_get_timezone_location(timezone_getter): tz = timezone_getter('America/St_Johns') assert (dates.get_timezone_location(tz, locale='de_DE') ==