Skip to content

Commit 7b8e62b

Browse files
Fix rounding of non-float numbers in _PyTime_ObjectToTimeval() and _PyTime_ObjectToTimespec()
The rounding mode was ignored: the fractional part was always rounded half to even. Add tests for conversion of Fraction, Decimal and other numbers with the numerator and denominator attributes in the C API. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 42e5b0c commit 7b8e62b

2 files changed

Lines changed: 83 additions & 1 deletion

File tree

‎Lib/test/test_time.py‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,13 @@ class _PyTime(enum.IntEnum):
5757
)
5858

5959

60+
class RatioNumber:
61+
"""A number which only has the numerator and denominator attributes."""
62+
def __init__(self, numerator, denominator):
63+
self.numerator = numerator
64+
self.denominator = denominator
65+
66+
6067
class TimeTestCase(unittest.TestCase):
6168

6269
def setUp(self):
@@ -1049,6 +1056,54 @@ def decimal_round(self, x):
10491056
d = d.quantize(1)
10501057
return int(d)
10511058

1059+
def check_ratio_rounding(self, pytime_converter, expected_func,
1060+
sec_to_unit, value_filter=None):
1061+
"""Test the conversion of numbers which are neither int nor float.
1062+
1063+
The number of seconds is converted exactly to the number of units
1064+
(sec_to_unit per second), rounded with the specified rounding mode
1065+
and passed to expected_func().
1066+
"""
1067+
exp = round(math.log10(sec_to_unit)) - 12
1068+
# Timestamps in picoseconds: rounding to a nanosecond is required.
1069+
ps_timestamps = sorted({ns * 1000 + delta
1070+
for ns in self._rounding_values(False)
1071+
for delta in (-501, -500, -499, -1, 0,
1072+
1, 499, 500, 501)})
1073+
for time_rnd, decimal_rnd in ROUNDING_MODES:
1074+
with decimal.localcontext() as context:
1075+
context.rounding = decimal_rnd
1076+
for ps in ps_timestamps:
1077+
units = int(decimal.Decimal(ps).scaleb(exp).quantize(1))
1078+
if value_filter and not value_filter(units // sec_to_unit):
1079+
continue
1080+
expected = expected_func(units)
1081+
for value in (fractions.Fraction(ps, 10**12),
1082+
decimal.Decimal(ps).scaleb(-12),
1083+
RatioNumber(ps, 10**12)):
1084+
debug_info = {'value': value, 'rounding': decimal_rnd}
1085+
self.assertEqual(pytime_converter(value, time_rnd),
1086+
expected, debug_info)
1087+
1088+
# test overflow
1089+
for time_rnd, _ in ROUNDING_MODES:
1090+
for seconds in (-self.OVERFLOW_SECONDS, self.OVERFLOW_SECONDS):
1091+
for value in (fractions.Fraction(seconds),
1092+
decimal.Decimal(seconds),
1093+
RatioNumber(seconds, 1)):
1094+
debug_info = {'value': value, 'rounding': time_rnd}
1095+
with self.assertRaises(OverflowError, msg=debug_info):
1096+
pytime_converter(value, time_rnd)
1097+
1098+
for time_rnd, _ in ROUNDING_MODES:
1099+
# test nan
1100+
with self.assertRaises(ValueError):
1101+
pytime_converter(decimal.Decimal('nan'), time_rnd)
1102+
# a type is not a number
1103+
for value in (int, fractions.Fraction, RatioNumber):
1104+
with self.assertRaisesRegex(TypeError, 'not type'):
1105+
pytime_converter(value, time_rnd)
1106+
10521107

10531108
class TestCPyTime(CPyTimeTestCase, unittest.TestCase):
10541109
"""
@@ -1084,6 +1139,11 @@ def test_FromSecondsObject(self):
10841139
_PyTime_FromSecondsObject,
10851140
lambda ns: self.decimal_round(ns * SEC_TO_NS))
10861141

1142+
self.check_ratio_rounding(
1143+
_PyTime_FromSecondsObject,
1144+
lambda ns: ns, SEC_TO_NS,
1145+
value_filter=lambda secs: PyTime_MIN <= secs * SEC_TO_NS <= PyTime_MAX)
1146+
10871147
# test nan
10881148
for time_rnd, _ in ROUNDING_MODES:
10891149
with self.assertRaises(ValueError):
@@ -1235,6 +1295,10 @@ def test_object_to_time_t(self):
12351295
self.decimal_round,
12361296
value_filter=self.time_t_filter)
12371297

1298+
self.check_ratio_rounding(_PyTime_ObjectToTime_t,
1299+
lambda secs: secs, 1,
1300+
value_filter=self.time_t_filter)
1301+
12381302
def create_converter(self, sec_to_unit):
12391303
def converter(secs):
12401304
floatpart, intpart = math.modf(secs)
@@ -1261,6 +1325,11 @@ def test_object_to_timeval(self):
12611325
self.create_converter(SEC_TO_US),
12621326
value_filter=self.time_t_filter)
12631327

1328+
self.check_ratio_rounding(_PyTime_ObjectToTimeval,
1329+
lambda units: divmod(units, SEC_TO_US),
1330+
SEC_TO_US,
1331+
value_filter=self.time_t_filter)
1332+
12641333
# test nan
12651334
for time_rnd, _ in ROUNDING_MODES:
12661335
with self.assertRaises(ValueError):
@@ -1277,6 +1346,11 @@ def test_object_to_timespec(self):
12771346
self.create_converter(SEC_TO_NS),
12781347
value_filter=self.time_t_filter)
12791348

1349+
self.check_ratio_rounding(_PyTime_ObjectToTimespec,
1350+
lambda units: divmod(units, SEC_TO_NS),
1351+
SEC_TO_NS,
1352+
value_filter=self.time_t_filter)
1353+
12801354
# test nan
12811355
for time_rnd, _ in ROUNDING_MODES:
12821356
with self.assertRaises(ValueError):

‎Python/pytime.c‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -615,11 +615,19 @@ pytime_ratio_to_denominator(PyObject *numerator, PyObject *denominator,
615615
Py_DECREF(divmod);
616616
return -1;
617617
}
618+
if (round == _PyTime_ROUND_UP) {
619+
/* The remainder is non-negative, so the direction of rounding
620+
depends on the sign of the whole number. */
621+
round = *sec < 0 ? _PyTime_ROUND_FLOOR : _PyTime_ROUND_CEILING;
622+
}
618623
PyObject *tmp = multiply_divide_and_round(scale,
619624
PyTuple_GET_ITEM(divmod, 1),
620625
denominator,
621-
_PyTime_ROUND_HALF_EVEN);
626+
round);
622627
Py_DECREF(divmod);
628+
if (tmp == NULL) {
629+
return -1;
630+
}
623631
*subsec = PyLong_AsLong(tmp);
624632
Py_DECREF(tmp);
625633
if (*subsec == -1 && PyErr_Occurred()) {

0 commit comments

Comments
 (0)