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
5 changes: 4 additions & 1 deletion babel/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -1646,7 +1646,10 @@ def format_frac_seconds(self, num: int) -> str:
of digits passed in.
"""
value = self.value.microsecond / 1000000
return self.format(round(value, num) * 10**num, num)
# Rounding can carry the value up to a whole second (for example 0.999
# rounds to 1.0), which would add a digit; clamp to the field width.
frac = min(int(round(value, num) * 10**num), 10**num - 1)
return self.format(frac, num)

def format_milliseconds_in_day(self, num):
msecs = (
Expand Down
8 changes: 8 additions & 0 deletions tests/test_dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,14 @@ def test_fractional_seconds_zero(self):
t = time(15, 30, 0)
assert dates.DateTimeFormat(t, locale='en_US')['SSSS'] == '0000'

def test_fractional_seconds_rounding_does_not_overflow_field(self):
t = time(1, 2, 3, 990000)
assert dates.DateTimeFormat(t, locale='en_US')['S'] == '9'
t = time(1, 2, 3, 999500)
assert dates.DateTimeFormat(t, locale='en_US')['SS'] == '99'
t = time(1, 2, 3, 999999)
assert dates.DateTimeFormat(t, locale='en_US')['SSSS'] == '9999'

def test_milliseconds_in_day(self):
t = time(15, 30, 12, 345000)
assert dates.DateTimeFormat(t, locale='en_US')['AAAA'] == '55812345'
Expand Down