Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions babel/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The short localized format does that too, but we don't support it (we only support ISO short). I'd like to add it in a follow up.

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(
Expand Down
15 changes: 14 additions & 1 deletion tests/test_dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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') ==
Expand Down
Loading