diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 47b7de04d7f95..15cdd10a8271d 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -146,6 +146,7 @@ Other API changes - :meth:`Series.unique` with dtype "timedelta64[ns]" or "datetime64[ns]" now returns :class:`TimedeltaArray` or :class:`DatetimeArray` instead of ``numpy.ndarray`` (:issue:`49176`) - Passing a sequence containing ``datetime`` objects and ``date`` objects to :class:`Series` constructor will return with ``object`` dtype instead of ``datetime64[ns]`` dtype, consistent with :class:`Index` behavior (:issue:`49341`) - Passing strings that cannot be parsed as datetimes to :class:`Series` or :class:`DataFrame` with ``dtype="datetime64[ns]"`` will raise instead of silently ignoring the keyword and returning ``object`` dtype (:issue:`24435`) +- :meth:`Series.astype` and :meth:`DataFrame.astype` casting to ``datetime64`` dtypes other than "s", "ms", "us", and "ns" now raise instead of silently returning ``datetime64[ns]`` (:issue:`49482`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/dtypes/astype.py b/pandas/core/dtypes/astype.py index 718badc2e4085..dfa0206f85caa 100644 --- a/pandas/core/dtypes/astype.py +++ b/pandas/core/dtypes/astype.py @@ -16,7 +16,6 @@ from pandas._libs.tslibs import ( get_unit_from_dtype, is_supported_unit, - is_unitless, ) from pandas._libs.tslibs.timedeltas import array_to_timedelta64 from pandas._typing import ( @@ -292,20 +291,6 @@ def astype_array_safe( # Ensure we don't end up with a PandasArray dtype = dtype.numpy_dtype - if ( - is_datetime64_dtype(values.dtype) - # need to do np.dtype check instead of is_datetime64_dtype - # otherwise pyright complains - and isinstance(dtype, np.dtype) - and dtype.kind == "M" - and not is_unitless(dtype) - and not is_dtype_equal(dtype, values.dtype) - and not is_supported_unit(get_unit_from_dtype(dtype)) - ): - # Supported units we handle in DatetimeArray.astype; but that raises - # on non-supported units, so we handle that here. - return np.asarray(values).astype(dtype) - try: new_values = astype_array(values, dtype, copy=copy) except (ValueError, TypeError): diff --git a/pandas/tests/frame/constructors/test_from_records.py b/pandas/tests/frame/constructors/test_from_records.py index b2efa0713b513..d038f608e9636 100644 --- a/pandas/tests/frame/constructors/test_from_records.py +++ b/pandas/tests/frame/constructors/test_from_records.py @@ -44,7 +44,8 @@ def test_from_records_with_datetimes(self): dtypes = [("EXPIRY", "