diff --git a/doc/release/upcoming_changes/16592.compatibility.rst b/doc/release/upcoming_changes/16592.compatibility.rst new file mode 100644 index 000000000000..0e2a79262ef6 --- /dev/null +++ b/doc/release/upcoming_changes/16592.compatibility.rst @@ -0,0 +1,7 @@ +float->timedelta promotion will raise a TypeError +------------------------------------------------- +Float and timedelta promotion consistently raises a TypeError. +``np.promote_types("float32", "m8")`` aligns with +``np.promote_types("m8", "float32")`` now and both raise a TypeError. +Previously, ``np.promote_types("float32", "m8")`` returned ``"m8"`` which +was considered a bug. diff --git a/numpy/core/src/multiarray/convert_datatype.c b/numpy/core/src/multiarray/convert_datatype.c index 0390c92fc3b7..6c1958e720ab 100644 --- a/numpy/core/src/multiarray/convert_datatype.c +++ b/numpy/core/src/multiarray/convert_datatype.c @@ -1419,8 +1419,7 @@ PyArray_PromoteTypes(PyArray_Descr *type1, PyArray_Descr *type2) } break; case NPY_TIMEDELTA: - if (PyTypeNum_ISINTEGER(type_num1) || - PyTypeNum_ISFLOAT(type_num1)) { + if (PyTypeNum_ISINTEGER(type_num1)) { return ensure_dtype_nbo(type2); } break; diff --git a/numpy/core/tests/test_datetime.py b/numpy/core/tests/test_datetime.py index 438d52f97f73..84dfc2949c96 100644 --- a/numpy/core/tests/test_datetime.py +++ b/numpy/core/tests/test_datetime.py @@ -775,6 +775,10 @@ def test_dtype_promotion(self): np.dtype('m8[Y]'), np.dtype('m8[D]')) assert_raises(TypeError, np.promote_types, np.dtype('m8[M]'), np.dtype('m8[W]')) + # timedelta and float cannot be safely cast with each other + assert_raises(TypeError, np.promote_types, "float32", "m8") + assert_raises(TypeError, np.promote_types, "m8", "float32") + # timedelta timedelta may overflow with big unit ranges assert_raises(OverflowError, np.promote_types, np.dtype('m8[W]'), np.dtype('m8[fs]'))