diff --git a/doc/source/whatsnew/v3.0.3.rst b/doc/source/whatsnew/v3.0.3.rst index 4df2161416e06..4e2d4e18b7a3a 100644 --- a/doc/source/whatsnew/v3.0.3.rst +++ b/doc/source/whatsnew/v3.0.3.rst @@ -15,6 +15,7 @@ Fixed regressions ~~~~~~~~~~~~~~~~~ - Fixed reading of Parquet files with timezone-aware timestamps or localizing of a timeseries with a ``pytz`` timezone when an older version of ``pytz`` was installed (:issue:`64978`) +- Fixed regression in :func:`to_timedelta` ignoring the ``unit`` argument for round float values when mixed with non-round floats in a list (:issue:`65150`) .. --------------------------------------------------------------------------- .. _whatsnew_303.bug_fixes: diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 77af30673e04d..7d0ce7c2de4b2 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -484,13 +484,15 @@ def array_to_timedelta64( if item == NPY_NAT: ival = NPY_NAT else: - ival = _numeric_to_td64ns(item, parsed_unit, int_reso) + # GH#65150 match the pattern in tslib.pyx: update creso + # first, then convert using creso as the output resolution. item_reso = int_reso - state.update_creso(item_reso) if infer_reso: creso = state.creso + ival = _numeric_to_td64ns(item, parsed_unit, creso) + elif is_float_object(item): int_item = int(item) if item == int_item: @@ -501,21 +503,20 @@ def array_to_timedelta64( if item == NPY_NAT: ival = NPY_NAT else: - ival = _numeric_to_td64ns(item, parsed_unit, int_reso) item_reso = int_reso - state.update_creso(item_reso) if infer_reso: creso = state.creso - else: - ival = _numeric_to_td64ns(item, parsed_unit, NPY_FR_ns) + ival = _numeric_to_td64ns(item, parsed_unit, creso) + else: item_reso = NPY_FR_ns - int_reso = NPY_FR_ns state.update_creso(item_reso) if infer_reso: creso = state.creso + ival = _numeric_to_td64ns(item, parsed_unit, creso) + else: raise TypeError(f"Invalid type for timedelta scalar: {type(item)}") diff --git a/pandas/tests/tools/test_to_timedelta.py b/pandas/tests/tools/test_to_timedelta.py index 784647a4d3697..ca799693cd146 100644 --- a/pandas/tests/tools/test_to_timedelta.py +++ b/pandas/tests/tools/test_to_timedelta.py @@ -358,6 +358,18 @@ def test_to_timedelta_unit_non_round_floats(self): result2 = to_timedelta(arr2, unit="s") assert result2.unit == "ns" + def test_to_timedelta_unit_mixed_round_and_non_round_floats(self): + # GH#65150 - round floats mixed with non-round floats should + # respect the unit for all values + expected = to_timedelta(["0 days 00:00:01", "0 days 00:00:01.01"]).as_unit("ns") + + result = to_timedelta([1.0, 1.01], unit="s") + tm.assert_index_equal(result, expected) + + # Also test integers mixed with non-round floats + result2 = to_timedelta([1, 1.01], unit="s") + tm.assert_index_equal(result2, expected) + def test_from_numeric_arrow_dtype(any_numeric_ea_dtype): # GH 52425