Skip to content
Merged
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
7 changes: 7 additions & 0 deletions Doc/whatsnew/3.16.rst
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,13 @@ Other language changes
:func:`asyncio.print_call_graph` can see through them into the awaited code.
(Contributed by Kumar Aditya in :gh:`157361`.)

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


Default interactive shell
=========================
Expand Down
2 changes: 2 additions & 0 deletions Include/internal/pycore_global_objects_fini_generated.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Include/internal/pycore_global_strings.h
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,7 @@ struct _Py_global_strings {
STRUCT_FOR_ID(default)
STRUCT_FOR_ID(defaultaction)
STRUCT_FOR_ID(delete)
STRUCT_FOR_ID(denominator)
STRUCT_FOR_ID(depth)
STRUCT_FOR_ID(desired_access)
STRUCT_FOR_ID(detect_types)
Expand Down Expand Up @@ -704,6 +705,7 @@ struct _Py_global_strings {
STRUCT_FOR_ID(nt)
STRUCT_FOR_ID(null)
STRUCT_FOR_ID(number)
STRUCT_FOR_ID(numerator)
STRUCT_FOR_ID(obj)
STRUCT_FOR_ID(object)
STRUCT_FOR_ID(offset)
Expand Down
2 changes: 2 additions & 0 deletions Include/internal/pycore_runtime_init_generated.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Include/internal/pycore_unicodeobject_generated.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 19 additions & 5 deletions Lib/_pydatetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -1792,14 +1792,28 @@ def _fromtimestamp(cls, t, utc, tz):

A timezone info object may be passed in as well.
"""
frac, t = _math.modf(t)
us = round(frac * 1e6)
if us >= 1000000:
if isinstance(t, float):
frac, t = _math.modf(t)
us = round(frac * 1e6)
else:
try:
try:
n, d = t.as_integer_ratio()
except AttributeError:
n = t.numerator
d = t.denominator
except AttributeError:
frac, t = _math.modf(t)
us = round(frac * 1e6)
else:
t, n = divmod(n, d)
us = _divide_and_round(n * 1_000_000, d)
if us >= 1_000_000:
t += 1
us -= 1000000
us -= 1_000_000
elif us < 0:
t -= 1
us += 1000000
us += 1_000_000

converter = _time.gmtime if utc else _time.localtime
y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
Expand Down
67 changes: 63 additions & 4 deletions Lib/test/datetimetester.py
Original file line number Diff line number Diff line change
Expand Up @@ -2999,11 +2999,11 @@ def utcfromtimestamp(*args, **kwargs):
self.assertEqual(t, zero)
t = fts(D('0.000_000_5'))
self.assertEqual(t, zero)
t = fts(D('0.000_000_500_000_000_000_000_1'))
t = fts(D('0.000_000_500_000_000_000_000_000_000_000_000_000_001'))
self.assertEqual(t, one)
t = fts(D('0.000_000_9'))
self.assertEqual(t, one)
t = fts(D('0.999_999_499_999_999_9'))
t = fts(D('0.999_999_499_999_999_999_999_999_999_999_999_999_999'))
self.assertEqual(t.second, 0)
self.assertEqual(t.microsecond, 999_999)
t = fts(D('0.999_999_5'))
Expand All @@ -3016,6 +3016,21 @@ def utcfromtimestamp(*args, **kwargs):
self.assertEqual(t.second, 0)
self.assertEqual(t.microsecond, 7812)

t = fts(D('2_147_475_000.000_000_5'))
self.assertEqual(t.second, 0)
self.assertEqual(t.microsecond, 0)
t = fts(D('2_147_475_000'
'.000_000_500_000_000_000_000_000_000_000_000_000_001'))
self.assertEqual(t.second, 0)
self.assertEqual(t.microsecond, 1)
t = fts(D('2_147_475_000'
'.999_999_499_999_999_999_999_999_999_999_999_999_999'))
self.assertEqual(t.second, 0)
self.assertEqual(t.microsecond, 999_999)
t = fts(D('2_147_475_000.999_999_5'))
self.assertEqual(t.second, 1)
self.assertEqual(t.microsecond, 0)

@support.run_with_tz('MSK-03') # Something east of Greenwich
def test_microsecond_rounding_fraction(self):
F = fractions.Fraction
Expand Down Expand Up @@ -3046,11 +3061,13 @@ def utcfromtimestamp(*args, **kwargs):
self.assertEqual(t, zero)
t = fts(F(5, 10_000_000))
self.assertEqual(t, zero)
t = fts(F(5_000_000_000, 9_999_999_999_999_999))
t = fts(F( 5_000_000_000_000_000_000_000_000_000_000_000,
9_999_999_999_999_999_999_999_999_999_999_999_999_999))
self.assertEqual(t, one)
t = fts(F(9, 10_000_000))
self.assertEqual(t, one)
t = fts(F(9_999_995_000_000_000, 10_000_000_000_000_001))
t = fts(F( 9_999_995_000_000_000_000_000_000_000_000_000_000_000,
10_000_000_000_000_000_000_000_000_000_000_000_000_001))
self.assertEqual(t.second, 0)
self.assertEqual(t.microsecond, 999_999)
t = fts(F(9_999_995, 10_000_000))
Expand All @@ -3063,6 +3080,48 @@ def utcfromtimestamp(*args, **kwargs):
self.assertEqual(t.second, 0)
self.assertEqual(t.microsecond, 7812)

t = fts(2_147_475_000 + F(5, 10_000_000))
self.assertEqual(t.second, 0)
self.assertEqual(t.microsecond, 0)
t = fts(2_147_475_000 +
F( 5_000_000_000_000_000_000_000_000_000_000_000,
9_999_999_999_999_999_999_999_999_999_999_999_999_999))
self.assertEqual(t.second, 0)
self.assertEqual(t.microsecond, 1)
t = fts(2_147_475_000 +
F( 9_999_995_000_000_000_000_000_000_000_000_000_000_000,
10_000_000_000_000_000_000_000_000_000_000_000_000_001))
self.assertEqual(t.second, 0)
self.assertEqual(t.microsecond, 999_999)
t = fts(2_147_475_000 + F(9_999_995, 10_000_000))
self.assertEqual(t.second, 1)
self.assertEqual(t.microsecond, 0)

@support.run_with_tz('MSK-03') # Something east of Greenwich
def test_microsecond_rounding_ratio(self):
# A number which only has the numerator and denominator attributes.
class Ratio:
def __init__(self, fraction):
self.numerator = fraction.numerator
self.denominator = fraction.denominator

F = fractions.Fraction
fts = self.theclass.fromtimestamp
for value in [
F(0), F(1, 1_000_000), F(-1, 1_000_000),
F(5, 10_000_000), F(-5, 10_000_000), F(15, 10_000_000),
2_147_475_000 + F(5, 10_000_000),
2_147_475_000 +
F( 5_000_000_000_000_000_000_000_000_000_000_000,
9_999_999_999_999_999_999_999_999_999_999_999_999_999),
2_147_475_000 +
F( 9_999_995_000_000_000_000_000_000_000_000_000_000_000,
10_000_000_000_000_000_000_000_000_000_000_000_000_001),
2_147_475_000 + F(9_999_995, 10_000_000),
]:
with self.subTest(value=value):
self.assertEqual(fts(Ratio(value)), fts(value))

def test_timestamp_limits(self):
with self.subTest("minimum UTC"):
min_dt = self.theclass.min.replace(tzinfo=timezone.utc)
Expand Down
8 changes: 2 additions & 6 deletions Lib/test/test_os/test_os.py
Original file line number Diff line number Diff line change
Expand Up @@ -1181,16 +1181,12 @@ def ns_to_sec(ns):
@staticmethod
def ns_to_sec_decimal(ns):
# Convert a number of nanosecond (int) to a number of seconds (Decimal).
# Round towards infinity by adding 0.5 nanosecond to avoid rounding
# issue, os.utime() rounds towards minus infinity.
return decimal.Decimal('1e-9') * ns + decimal.Decimal('0.5e-9')
return decimal.Decimal('1e-9') * ns

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

def test_utime_by_indexed(self):
# pass times as floating-point seconds as the second indexed parameter
Expand Down
74 changes: 74 additions & 0 deletions Lib/test/test_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ class _PyTime(enum.IntEnum):
)


class RatioNumber:
"""A number which only has the numerator and denominator attributes."""
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator


class TimeTestCase(unittest.TestCase):

def setUp(self):
Expand Down Expand Up @@ -1049,6 +1056,54 @@ def decimal_round(self, x):
d = d.quantize(1)
return int(d)

def check_ratio_rounding(self, pytime_converter, expected_func,
sec_to_unit, value_filter=None):
"""Test the conversion of numbers which are neither int nor float.

The number of seconds is converted exactly to the number of units
(sec_to_unit per second), rounded with the specified rounding mode
and passed to expected_func().
"""
exp = round(math.log10(sec_to_unit)) - 12
# Timestamps in picoseconds: rounding to a nanosecond is required.
ps_timestamps = sorted({ns * 1000 + delta
for ns in self._rounding_values(False)
for delta in (-501, -500, -499, -1, 0,
1, 499, 500, 501)})
for time_rnd, decimal_rnd in ROUNDING_MODES:
with decimal.localcontext() as context:
context.rounding = decimal_rnd
for ps in ps_timestamps:
units = int(decimal.Decimal(ps).scaleb(exp).quantize(1))
if value_filter and not value_filter(units // sec_to_unit):
continue
expected = expected_func(units)
for value in (fractions.Fraction(ps, 10**12),
decimal.Decimal(ps).scaleb(-12),
RatioNumber(ps, 10**12)):
debug_info = {'value': value, 'rounding': decimal_rnd}
self.assertEqual(pytime_converter(value, time_rnd),
expected, debug_info)

# test overflow
for time_rnd, _ in ROUNDING_MODES:
for seconds in (-self.OVERFLOW_SECONDS, self.OVERFLOW_SECONDS):
for value in (fractions.Fraction(seconds),
decimal.Decimal(seconds),
RatioNumber(seconds, 1)):
debug_info = {'value': value, 'rounding': time_rnd}
with self.assertRaises(OverflowError, msg=debug_info):
pytime_converter(value, time_rnd)

for time_rnd, _ in ROUNDING_MODES:
# test nan
with self.assertRaises(ValueError):
pytime_converter(decimal.Decimal('nan'), time_rnd)
# a type is not a number
for value in (int, fractions.Fraction, RatioNumber):
with self.assertRaisesRegex(TypeError, 'must be real number'):
pytime_converter(value, time_rnd)


class TestCPyTime(CPyTimeTestCase, unittest.TestCase):
"""
Expand Down Expand Up @@ -1084,6 +1139,11 @@ def test_FromSecondsObject(self):
_PyTime_FromSecondsObject,
lambda ns: self.decimal_round(ns * SEC_TO_NS))

self.check_ratio_rounding(
_PyTime_FromSecondsObject,
lambda ns: ns, SEC_TO_NS,
value_filter=lambda secs: PyTime_MIN <= secs * SEC_TO_NS <= PyTime_MAX)

# test nan
for time_rnd, _ in ROUNDING_MODES:
with self.assertRaises(ValueError):
Expand Down Expand Up @@ -1235,6 +1295,10 @@ def test_object_to_time_t(self):
self.decimal_round,
value_filter=self.time_t_filter)

self.check_ratio_rounding(_PyTime_ObjectToTime_t,
lambda secs: secs, 1,
value_filter=self.time_t_filter)

def create_converter(self, sec_to_unit):
def converter(secs):
floatpart, intpart = math.modf(secs)
Expand All @@ -1261,6 +1325,11 @@ def test_object_to_timeval(self):
self.create_converter(SEC_TO_US),
value_filter=self.time_t_filter)

self.check_ratio_rounding(_PyTime_ObjectToTimeval,
lambda units: divmod(units, SEC_TO_US),
SEC_TO_US,
value_filter=self.time_t_filter)

# test nan
for time_rnd, _ in ROUNDING_MODES:
with self.assertRaises(ValueError):
Expand All @@ -1277,6 +1346,11 @@ def test_object_to_timespec(self):
self.create_converter(SEC_TO_NS),
value_filter=self.time_t_filter)

self.check_ratio_rounding(_PyTime_ObjectToTimespec,
lambda units: divmod(units, SEC_TO_NS),
SEC_TO_NS,
value_filter=self.time_t_filter)

# test nan
for time_rnd, _ in ROUNDING_MODES:
with self.assertRaises(ValueError):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Avoid the precision loss caused by the :class:`float` type in functions that
take more precise numbers (such as :class:`~decimal.Decimal` and
:class:`~fractions.Fraction`) as timestamp or timeout arguments.
Loading
Loading