Skip to content

format_datetime prints "None" for the 'O' time zone field #1478

Open

Description

@matthewalberto

Overview Description

A date pattern with a single O (short localized GMT format, e.g. "GMT-8") prints the word None instead of the offset. OOOO works. The pattern is accepted without error, so the bad output is easy to miss.

Steps to Reproduce

from datetime import datetime
from zoneinfo import ZoneInfo
from babel.dates import format_datetime, format_time

dt = datetime(2016, 1, 13, 7, 8, 35, tzinfo=ZoneInfo('America/Los_Angeles'))
print(format_datetime(dt, 'h:mm a O', locale='en'))
print(format_time(dt, 'HH:mm O', locale='en'))
print(format_datetime(dt, 'OOOO', locale='en'))

Actual Results

7:08 AM None
07:08 None
GMT-08:00

Expected Results

7:08 AM GMT-8
07:08 GMT-8
GMT-08:00

UTS #35 defines O as the short localized GMT format: hours without a leading zero, minutes only when not zero (GMT-8, GMT+5:30), inside the locale's GMT format (UTC-8 in fr).

Reproducibility

Always. Babel 2.18.0 and master (aeca9fa), Python 3.13, Windows; with pytz or zoneinfo.

Additional Information

DateTimeFormat.format_timezone in babel/dates.py handles OOOO and then falls through for O (there is a # TODO: To add support for O:1 comment), so it returns None, which ends up in the string. PATTERN_CHARS lists 'O': [1, 4], so the pattern passes validation.

Open PR #1284 adds a private _get_timezone_gmt_short helper (used there for the z fallback) that produces exactly this format. Once that lands, O could call it with a one-line change in format_timezone. I'm happy to send that follow-up with tests if it helps.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions