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
34 changes: 30 additions & 4 deletions babel/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,7 @@ def get_time_format(

def get_timezone_gmt(
datetime: _Instant = None,
width: Literal['long', 'short', 'iso8601', 'iso8601_short'] = 'long',
width: Literal['long', 'short', 'localized_short', 'iso8601', 'iso8601_short'] = 'long',
locale: Locale | str | None = None,
return_z: bool = False,
# TODO(3.0): Make return_z kw-only too
Expand All @@ -476,7 +476,7 @@ def get_timezone_gmt(
"""Return the timezone associated with the given `datetime` object formatted
as string indicating the offset from GMT.

>>> from datetime import datetime
>>> from datetime import datetime, timedelta, timezone
>>> dt = datetime(2007, 4, 1, 15, 30)
>>> get_timezone_gmt(dt, locale='en')
'GMT+00:00'
Expand Down Expand Up @@ -507,11 +507,25 @@ def get_timezone_gmt(
>>> get_timezone_gmt(dt, locale='ar', utc=True)
'التوقيت العالمي -07:00'

The "localized_short" width gives the short localized GMT format used by
the ``O`` date pattern field: no leading zero on the hours, and the
minutes and seconds only when they are nonzero. Historical timezones may
carry seconds in their UTC offset, so Paris in 1890 is rendered in full
instead of truncated to the minute:

>>> from datetime import timedelta, timezone
>>> dt = datetime(1890, 1, 1, 12, 0, tzinfo=timezone(timedelta(minutes=9, seconds=21)))
>>> get_timezone_gmt(dt, locale='en', width='localized_short')
'GMT+0:09:21'
>>> get_timezone_gmt(dt, locale='fr_FR', width='localized_short')
'UTC+0:09:21'

.. versionadded:: 0.9

:param datetime: the ``datetime`` object; if `None`, the current date and
time in UTC is used
:param width: either "long" or "short" or "iso8601" or "iso8601_short"
:param width: either "long", "short", "localized_short", "iso8601"
or "iso8601_short"
:param locale: the `Locale` object, or a locale string. Defaults to the system time locale.
:param return_z: True or False; Function returns indicator "Z"
when local time offset is 0
Expand All @@ -530,6 +544,18 @@ def get_timezone_gmt(
return 'Z'
sign = '-' if seconds < 0 else '+'
hours, seconds = divmod(abs(seconds), 3600)
if width == 'localized_short':
# The short localized GMT format: no leading zero on the hours, and
# the minutes and seconds only when nonzero. Historical timezones may
# carry seconds in their UTC offset, so they are kept instead of
# truncated away.
minutes, seconds = divmod(seconds, 60)
offset_string = f"{sign}{hours}"
if minutes or seconds:
offset_string += f":{minutes:02d}"
if seconds:
offset_string += f":{seconds:02d}"
return locale.zone_formats['gmt'] % offset_string
if seconds == 0 and width == 'iso8601_short':
return '%s%02d' % (sign, hours)
elif width == 'short' or width == 'iso8601_short':
Expand Down Expand Up @@ -1851,7 +1877,7 @@ def format_timezone(self, char: str, num: int) -> str:
elif char == 'O':
if num == 4:
return get_timezone_gmt(value, width, locale=self.locale)
# TODO: To add support for O:1
return get_timezone_gmt(value, 'localized_short', locale=self.locale) # fmt: skip
elif char == 'v':
return get_timezone_name(value.tzinfo, width, locale=self.locale)
elif char == 'V':
Expand Down
34 changes: 33 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 @@ -75,6 +75,7 @@ def test_format_datetime_timezone_formats_los_angeles(timezone_getter):
assert dates.format_datetime(dt, 'ZZZ', locale='en') == '-0800'
assert dates.format_datetime(dt, 'ZZZZ', locale='en') == 'GMT-08:00'
assert dates.format_datetime(dt, 'ZZZZZ', locale='en') == '-08:00'
assert dates.format_datetime(dt, 'O', locale='en') == 'GMT-8'
assert dates.format_datetime(dt, 'OOOO', locale='en') == 'GMT-08:00'
assert dates.format_datetime(dt, 'VV', locale='en') == 'America/Los_Angeles'
assert dates.format_datetime(dt, 'VVV', locale='en') == 'Los Angeles'
Expand All @@ -98,6 +99,7 @@ def test_format_datetime_timezone_formats_utc(timezone_getter):
assert dates.format_datetime(dt, 'ZZZ', locale='en') == '+0000'
assert dates.format_datetime(dt, 'ZZZZ', locale='en') == 'GMT+00:00'
assert dates.format_datetime(dt, 'ZZZZZ', locale='en') == 'Z'
assert dates.format_datetime(dt, 'O', locale='en') == 'GMT+0'
assert dates.format_datetime(dt, 'OOOO', locale='en') == 'GMT+00:00'
assert dates.format_datetime(dt, 'VV', locale='en') == 'Etc/UTC'
assert dates.format_datetime(dt, 'VVV', locale='en') == 'UTC'
Expand All @@ -119,6 +121,7 @@ def test_format_datetime_timezone_formats_kolkata(timezone_getter):
assert dates.format_datetime(dt, 'zzzz', locale='en') == 'India Standard Time'
assert dates.format_datetime(dt, 'ZZZZ', locale='en') == 'GMT+05:30'
assert dates.format_datetime(dt, 'ZZZZZ', locale='en') == '+05:30'
assert dates.format_datetime(dt, 'O', locale='en') == 'GMT+5:30'
assert dates.format_datetime(dt, 'OOOO', locale='en') == 'GMT+05:30'
assert dates.format_datetime(dt, 'VV', locale='en') == 'Asia/Kolkata'
assert dates.format_datetime(dt, 'VVV', locale='en') == 'Kolkata'
Expand All @@ -134,6 +137,35 @@ def test_format_datetime_timezone_formats_kolkata(timezone_getter):
assert dates.format_datetime(dt, 'xxxxx', locale='en') == '+05:30'


def test_format_datetime_timezone_short_gmt_localized(timezone_getter):
# The short localized GMT format (O) wraps the offset in the locale's
# own GMT format, e.g. UTC−8 in French.
tz = timezone_getter('America/Los_Angeles')
dt = _localize(tz, datetime(2016, 1, 13, 7, 8, 35))
assert dates.format_datetime(dt, 'h:mm a O', locale='en') == '7:08 AM GMT-8'
assert dates.format_time(dt, 'HH:mm O', locale='en') == '07:08 GMT-8'
assert dates.format_datetime(dt, 'O', locale='fr_FR') == 'UTC-8'


def test_format_datetime_timezone_short_gmt_localized_with_seconds():
# Historical timezones can have a UTC offset with a seconds part, e.g.
# Europe/Paris in 1890 was UTC+00:09:21 (the "Paris mean time" offset).
# The short localized GMT format keeps the seconds, like ICU's
# `shortOffset` does (UTS #35, localized GMT format).
tz = timezone(timedelta(minutes=9, seconds=21))
dt = datetime(1890, 6, 1, 12, 0, tzinfo=tz)
assert dates.format_datetime(dt, 'O', locale='en_US') == 'GMT+0:09:21'
assert dates.format_datetime(dt, 'h:mm a O', locale='en_US') == '12:00 PM GMT+0:09:21'
# The locale's own GMT format is still applied.
assert dates.format_datetime(dt, 'O', locale='fr_FR') == 'UTC+0:09:21'
# The long localized GMT format (OOOO) is unaffected and keeps its
# existing hours:minutes output.
assert dates.format_datetime(dt, 'OOOO', locale='en_US') == 'GMT+00:09'
# Negative offsets with seconds keep the sign and both parts.
dt = datetime(1890, 6, 1, 12, 0, tzinfo=timezone(-timedelta(minutes=9, seconds=21)))
assert dates.format_datetime(dt, 'O', locale='en_US') == 'GMT-0:09:21'


def test_format_time_with_naive_datetime_and_tzinfo(timezone_getter):
d = datetime(2007, 4, 1, 15, 30)
formatted = dates.format_time(d, 'long', tzinfo=timezone_getter('US/Eastern'), locale='en')
Expand Down