From cbf5299a065e20a5b129ad5eed6953262ce54f37 Mon Sep 17 00:00:00 2001
From: Elliott Sales de Andrade <quantum.analyst@gmail.com>
Date: Wed, 21 Feb 2024 06:55:19 -0500
Subject: [PATCH 6/6] Fix accidental loss-of-precision for to_datetime(str,
unit=...)
In Pandas 1.5.3, the `float(val)` cast was inline to the
`cast_from_unit` call in `array_with_unit_to_datetime`. This caused the
intermediate (unnamed) value to be a Python float.
Since #50301, a temporary variable was added to avoid multiple casts,
but with explicit type `cdef float`, which defines a _Cython_ float.
This type is 32-bit, and causes a loss of precision, and a regression in
parsing from 1.5.3.
So widen the explicit type of the temporary `fval` variable to (64-bit)
`double`, which will not lose precision.
Fixes #57051
Signed-off-by: Elliott Sales de Andrade <quantum.analyst@gmail.com>
---
pandas/_libs/tslib.pyx | 2 +-
pandas/tests/tools/test_to_datetime.py | 8 ++++++++
2 files changed, 9 insertions(+), 1 deletion(-)
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index 017fdc4bc8..dd23c2f27c 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -277,7 +277,7 @@ def array_with_unit_to_datetime(
bint is_raise = errors == "raise"
ndarray[int64_t] iresult
tzinfo tz = None
- float fval
+ double fval
assert is_ignore or is_coerce or is_raise
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index 6791ac0340..a4194dcff2 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -1912,6 +1912,14 @@ class TestToDatetimeUnit:
with pytest.raises(ValueError, match=msg):
to_datetime([1], unit="D", format="%Y%m%d", cache=cache)
+ def test_unit_str(self, cache):
+ # GH 57051
+ # Test that strs aren't dropping precision to 32-bit accidentally.
+ with tm.assert_produces_warning(FutureWarning):
+ res = pd.to_datetime(["1704660000"], unit="s", origin="unix")
+ expected = pd.to_datetime([1704660000], unit="s", origin="unix")
+ tm.assert_index_equal(res, expected)
+
def test_unit_array_mixed_nans(self, cache):
values = [11111111111111111, 1, 1.0, iNaT, NaT, np.nan, "NaT", ""]
result = to_datetime(values, unit="D", errors="ignore", cache=cache)
--
2.43.0