Skip to content

Commit e165582

Browse files
committed
Fix timeZone handling for time arguments
1 parent 870b926 commit e165582

2 files changed

Lines changed: 27 additions & 6 deletions

File tree

fluent.runtime/fluent/runtime/types.py

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -371,7 +371,9 @@ def format(self, locale: Locale) -> str:
371371
return format_date(selftz, format="medium", locale=locale)
372372
else:
373373
return format_time(selftz, format=ts or "short", locale=locale)
374-
elif ts is None:
374+
assert not isinstance(selftz, time)
375+
376+
if ts is None:
375377
return format_date(selftz, format=ds, locale=locale)
376378

377379
# Both date and time. Logic copied from babel.dates.format_datetime,
@@ -388,13 +390,24 @@ def format(self, locale: Locale) -> str:
388390

389391
def _ensure_datetime_tzinfo(dt: Union[datetime, time], tzinfo: Union[str, None] = None) -> Union[datetime, time]:
390392
"""
391-
Ensure the datetime passed has an attached tzinfo.
393+
Ensure the datetime or time passed has an attached tzinfo.
392394
"""
393-
# Adapted from babel's function.
395+
if isinstance(dt, datetime):
396+
# Adapted from babel's function.
397+
if dt.tzinfo is None:
398+
dt = dt.replace(tzinfo=pytz.UTC)
399+
if tzinfo is not None:
400+
dt = dt.astimezone(get_timezone(tzinfo))
401+
return dt
394402
if dt.tzinfo is None:
395-
dt = dt.replace(tzinfo=pytz.UTC)
396-
if tzinfo is not None:
397-
dt = dt.astimezone(get_timezone(tzinfo))
403+
tz = get_timezone(tzinfo) if tzinfo is not None else pytz.UTC
404+
return dt.replace(tzinfo=tz)
405+
elif tzinfo is not None:
406+
tz = get_timezone(tzinfo)
407+
if tz != dt.tzinfo:
408+
print(dt.tzinfo, tz)
409+
raise TypeError("timezone conversion not supported for time values")
410+
398411
return dt
399412

400413

fluent.runtime/tests/test_types.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,14 @@ def test_timeZone(self):
288288
fd2d = fluent_date(dt1, timeStyle="short", timeZone="Europe/London")
289289
assert fd2d.format(en_GB) == "00:30"
290290

291+
ft = fluent_date(a_time, timeZone="UTC")
292+
assert ft.format(en_GB) == "10:31"
293+
ft = fluent_date(a_time, timeZone="Europe/London")
294+
with pytest.raises(TypeError):
295+
ft.format(en_GB)
296+
ft = fluent_date(time(10, 31, 00, 333), timeZone="Europe/London")
297+
assert ft.format(en_GB) == "10:31"
298+
291299
def test_allow_unsupported_options(self):
292300
# We are just checking that these don't raise exceptions
293301
with warnings.catch_warnings():

0 commit comments

Comments
 (0)