Skip to content

Commit f4b3d2b

Browse files
gh-67795: Improve precision of non-float timestamp and timeout arguments (GH-139273)
Numbers like Decimal and Fraction are now converted exactly using as_integer_ratio() or the numerator and denominator attributes, instead of being converted to float first. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4f5d201 commit f4b3d2b

11 files changed

Lines changed: 526 additions & 47 deletions

‎Doc/whatsnew/3.16.rst‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,13 @@ Other language changes
139139
:func:`asyncio.print_call_graph` can see through them into the awaited code.
140140
(Contributed by Kumar Aditya in :gh:`157361`.)
141141

142+
* Functions that take timestamp or timeout arguments
143+
no longer convert numbers other than integers and floats
144+
(such as :class:`~decimal.Decimal` and :class:`~fractions.Fraction`)
145+
to :class:`float`.
146+
They are converted exactly, which avoids the precision loss.
147+
(Contributed by Serhiy Storchaka in :gh:`67795`.)
148+
142149

143150
Default interactive shell
144151
=========================

‎Include/internal/pycore_global_objects_fini_generated.h‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Include/internal/pycore_global_strings.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,7 @@ struct _Py_global_strings {
436436
STRUCT_FOR_ID(default)
437437
STRUCT_FOR_ID(defaultaction)
438438
STRUCT_FOR_ID(delete)
439+
STRUCT_FOR_ID(denominator)
439440
STRUCT_FOR_ID(depth)
440441
STRUCT_FOR_ID(desired_access)
441442
STRUCT_FOR_ID(detect_types)
@@ -704,6 +705,7 @@ struct _Py_global_strings {
704705
STRUCT_FOR_ID(nt)
705706
STRUCT_FOR_ID(null)
706707
STRUCT_FOR_ID(number)
708+
STRUCT_FOR_ID(numerator)
707709
STRUCT_FOR_ID(obj)
708710
STRUCT_FOR_ID(object)
709711
STRUCT_FOR_ID(offset)

‎Include/internal/pycore_runtime_init_generated.h‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Include/internal/pycore_unicodeobject_generated.h‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Lib/_pydatetime.py‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1792,14 +1792,28 @@ def _fromtimestamp(cls, t, utc, tz):
17921792
17931793
A timezone info object may be passed in as well.
17941794
"""
1795-
frac, t = _math.modf(t)
1796-
us = round(frac * 1e6)
1797-
if us >= 1000000:
1795+
if isinstance(t, float):
1796+
frac, t = _math.modf(t)
1797+
us = round(frac * 1e6)
1798+
else:
1799+
try:
1800+
try:
1801+
n, d = t.as_integer_ratio()
1802+
except AttributeError:
1803+
n = t.numerator
1804+
d = t.denominator
1805+
except AttributeError:
1806+
frac, t = _math.modf(t)
1807+
us = round(frac * 1e6)
1808+
else:
1809+
t, n = divmod(n, d)
1810+
us = _divide_and_round(n * 1_000_000, d)
1811+
if us >= 1_000_000:
17981812
t += 1
1799-
us -= 1000000
1813+
us -= 1_000_000
18001814
elif us < 0:
18011815
t -= 1
1802-
us += 1000000
1816+
us += 1_000_000
18031817

18041818
converter = _time.gmtime if utc else _time.localtime
18051819
y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)

‎Lib/test/datetimetester.py‎

Lines changed: 63 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2999,11 +2999,11 @@ def utcfromtimestamp(*args, **kwargs):
29992999
self.assertEqual(t, zero)
30003000
t = fts(D('0.000_000_5'))
30013001
self.assertEqual(t, zero)
3002-
t = fts(D('0.000_000_500_000_000_000_000_1'))
3002+
t = fts(D('0.000_000_500_000_000_000_000_000_000_000_000_000_001'))
30033003
self.assertEqual(t, one)
30043004
t = fts(D('0.000_000_9'))
30053005
self.assertEqual(t, one)
3006-
t = fts(D('0.999_999_499_999_999_9'))
3006+
t = fts(D('0.999_999_499_999_999_999_999_999_999_999_999_999_999'))
30073007
self.assertEqual(t.second, 0)
30083008
self.assertEqual(t.microsecond, 999_999)
30093009
t = fts(D('0.999_999_5'))
@@ -3016,6 +3016,21 @@ def utcfromtimestamp(*args, **kwargs):
30163016
self.assertEqual(t.second, 0)
30173017
self.assertEqual(t.microsecond, 7812)
30183018

3019+
t = fts(D('2_147_475_000.000_000_5'))
3020+
self.assertEqual(t.second, 0)
3021+
self.assertEqual(t.microsecond, 0)
3022+
t = fts(D('2_147_475_000'
3023+
'.000_000_500_000_000_000_000_000_000_000_000_000_001'))
3024+
self.assertEqual(t.second, 0)
3025+
self.assertEqual(t.microsecond, 1)
3026+
t = fts(D('2_147_475_000'
3027+
'.999_999_499_999_999_999_999_999_999_999_999_999_999'))
3028+
self.assertEqual(t.second, 0)
3029+
self.assertEqual(t.microsecond, 999_999)
3030+
t = fts(D('2_147_475_000.999_999_5'))
3031+
self.assertEqual(t.second, 1)
3032+
self.assertEqual(t.microsecond, 0)
3033+
30193034
@support.run_with_tz('MSK-03') # Something east of Greenwich
30203035
def test_microsecond_rounding_fraction(self):
30213036
F = fractions.Fraction
@@ -3046,11 +3061,13 @@ def utcfromtimestamp(*args, **kwargs):
30463061
self.assertEqual(t, zero)
30473062
t = fts(F(5, 10_000_000))
30483063
self.assertEqual(t, zero)
3049-
t = fts(F(5_000_000_000, 9_999_999_999_999_999))
3064+
t = fts(F( 5_000_000_000_000_000_000_000_000_000_000_000,
3065+
9_999_999_999_999_999_999_999_999_999_999_999_999_999))
30503066
self.assertEqual(t, one)
30513067
t = fts(F(9, 10_000_000))
30523068
self.assertEqual(t, one)
3053-
t = fts(F(9_999_995_000_000_000, 10_000_000_000_000_001))
3069+
t = fts(F( 9_999_995_000_000_000_000_000_000_000_000_000_000_000,
3070+
10_000_000_000_000_000_000_000_000_000_000_000_000_001))
30543071
self.assertEqual(t.second, 0)
30553072
self.assertEqual(t.microsecond, 999_999)
30563073
t = fts(F(9_999_995, 10_000_000))
@@ -3063,6 +3080,48 @@ def utcfromtimestamp(*args, **kwargs):
30633080
self.assertEqual(t.second, 0)
30643081
self.assertEqual(t.microsecond, 7812)
30653082

3083+
t = fts(2_147_475_000 + F(5, 10_000_000))
3084+
self.assertEqual(t.second, 0)
3085+
self.assertEqual(t.microsecond, 0)
3086+
t = fts(2_147_475_000 +
3087+
F( 5_000_000_000_000_000_000_000_000_000_000_000,
3088+
9_999_999_999_999_999_999_999_999_999_999_999_999_999))
3089+
self.assertEqual(t.second, 0)
3090+
self.assertEqual(t.microsecond, 1)
3091+
t = fts(2_147_475_000 +
3092+
F( 9_999_995_000_000_000_000_000_000_000_000_000_000_000,
3093+
10_000_000_000_000_000_000_000_000_000_000_000_000_001))
3094+
self.assertEqual(t.second, 0)
3095+
self.assertEqual(t.microsecond, 999_999)
3096+
t = fts(2_147_475_000 + F(9_999_995, 10_000_000))
3097+
self.assertEqual(t.second, 1)
3098+
self.assertEqual(t.microsecond, 0)
3099+
3100+
@support.run_with_tz('MSK-03') # Something east of Greenwich
3101+
def test_microsecond_rounding_ratio(self):
3102+
# A number which only has the numerator and denominator attributes.
3103+
class Ratio:
3104+
def __init__(self, fraction):
3105+
self.numerator = fraction.numerator
3106+
self.denominator = fraction.denominator
3107+
3108+
F = fractions.Fraction
3109+
fts = self.theclass.fromtimestamp
3110+
for value in [
3111+
F(0), F(1, 1_000_000), F(-1, 1_000_000),
3112+
F(5, 10_000_000), F(-5, 10_000_000), F(15, 10_000_000),
3113+
2_147_475_000 + F(5, 10_000_000),
3114+
2_147_475_000 +
3115+
F( 5_000_000_000_000_000_000_000_000_000_000_000,
3116+
9_999_999_999_999_999_999_999_999_999_999_999_999_999),
3117+
2_147_475_000 +
3118+
F( 9_999_995_000_000_000_000_000_000_000_000_000_000_000,
3119+
10_000_000_000_000_000_000_000_000_000_000_000_000_001),
3120+
2_147_475_000 + F(9_999_995, 10_000_000),
3121+
]:
3122+
with self.subTest(value=value):
3123+
self.assertEqual(fts(Ratio(value)), fts(value))
3124+
30663125
def test_timestamp_limits(self):
30673126
with self.subTest("minimum UTC"):
30683127
min_dt = self.theclass.min.replace(tzinfo=timezone.utc)

‎Lib/test/test_os/test_os.py‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1181,16 +1181,12 @@ def ns_to_sec(ns):
11811181
@staticmethod
11821182
def ns_to_sec_decimal(ns):
11831183
# Convert a number of nanosecond (int) to a number of seconds (Decimal).
1184-
# Round towards infinity by adding 0.5 nanosecond to avoid rounding
1185-
# issue, os.utime() rounds towards minus infinity.
1186-
return decimal.Decimal('1e-9') * ns + decimal.Decimal('0.5e-9')
1184+
return decimal.Decimal('1e-9') * ns
11871185

11881186
@staticmethod
11891187
def ns_to_sec_fraction(ns):
11901188
# Convert a number of nanosecond (int) to a number of seconds (Fraction).
1191-
# Round towards infinity by adding 0.5 nanosecond to avoid rounding
1192-
# issue, os.utime() rounds towards minus infinity.
1193-
return fractions.Fraction(ns, 10**9) + fractions.Fraction(1, 2*10**9)
1189+
return fractions.Fraction(ns, 10**9)
11941190

11951191
def test_utime_by_indexed(self):
11961192
# pass times as floating-point seconds as the second indexed parameter

‎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, 'must be real number'):
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):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Avoid the precision loss caused by the :class:`float` type in functions that
2+
take more precise numbers (such as :class:`~decimal.Decimal` and
3+
:class:`~fractions.Fraction`) as timestamp or timeout arguments.

0 commit comments

Comments
 (0)