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
26 changes: 18 additions & 8 deletions babel/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,8 @@ def _get_time(
elif isinstance(time, (int, float)):
time = datetime.datetime.fromtimestamp(time, UTC)

if time.tzinfo is None:
time_had_tzinfo = time.tzinfo is not None
if not time_had_tzinfo:
time = time.replace(tzinfo=UTC)

if isinstance(time, datetime.datetime):
Expand All @@ -214,7 +215,17 @@ def _get_time(
time = tzinfo.normalize(time)
time = time.timetz()
elif tzinfo is not None:
time = time.replace(tzinfo=tzinfo)
if time_had_tzinfo:
# ``datetime.time`` has no ``astimezone``, and converting between
# time zones needs a date to resolve DST. Anchor the wall time to
# today's date and convert that, mirroring the ``datetime`` branch.
anchored = datetime.datetime.combine(datetime.date.today(), time)
converted = anchored.astimezone(tzinfo)
if hasattr(tzinfo, 'normalize'): # pytz
converted = tzinfo.normalize(converted)
time = converted.timetz()
else:
time = time.replace(tzinfo=tzinfo)
return time


Expand Down Expand Up @@ -908,12 +919,11 @@ def format_time(
``datetime`` is "naive" (i.e. it has no associated timezone information),
it is assumed to be in UTC.

These timezone calculations are **not** performed if the value is of type
``datetime.time``, as without date information there's no way to determine
what a given time would translate to in a different timezone without
information about whether daylight savings time is in effect or not. This
means that time values are left as-is, and the value of the `tzinfo`
parameter is only used to display the timezone name if needed:
``datetime.time`` values carry no date, which is needed to know whether
daylight saving time applies. If the value is already tz-aware, it is
converted using the current date as the reference. A naive ``datetime.time``
is left as-is, and the value of the `tzinfo` parameter is only used to
display the timezone name if needed:

>>> t = time(15, 30)
>>> format_time(t, format='full', tzinfo=get_timezone('Europe/Paris'),
Expand Down
42 changes: 41 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 pytest

Expand Down Expand Up @@ -678,6 +678,46 @@ def test_format_time(timezone_getter):
assert us_east == '3:30:00\u202fPM Eastern Standard Time'


def test_format_time_with_tz_aware_time():
# Regression test for #545: an aware time is converted to the requested
# timezone instead of being relabeled with it.
assert dates.format_time(
time(12, 0, tzinfo=timezone(timedelta(hours=2))),
"HH:mm",
tzinfo=timezone.utc,
locale="en_US",
) == "10:00"

# Without a target timezone the wall time is left as-is.
assert dates.format_time(
time(12, 0, tzinfo=timezone(timedelta(hours=2))),
"HH:mm",
locale="en_US",
) == "12:00"

# Naive times keep their wall time; the tzinfo only provides the label.
assert dates.format_time(
time(12, 0),
"HH:mm",
tzinfo=timezone.utc,
locale="en_US",
) == "12:00"


def test_format_time_with_tz_aware_time_and_dst():
pytz = pytest.importorskip("pytz")
with freeze_time("2023-01-01"):
paris = pytz.timezone("Europe/Paris")
eastern = pytz.timezone("US/Eastern")
paris_time = _localize(paris, datetime(2023, 1, 1, 15, 30)).timetz()
assert dates.format_time(
paris_time,
"HH:mm",
tzinfo=eastern,
locale="en_US",
) == "09:30"


def test_format_skeleton(timezone_getter):
dt = datetime(2007, 4, 1, 15, 30)
assert (dates.format_skeleton('yMEd', dt, locale='en_US') == 'Sun, 4/1/2007')
Expand Down