Skip to content

Commit ed9d7f0

Browse files
committed
Fix issue 27395
1 parent 6813d77 commit ed9d7f0

File tree

3 files changed

+15
-3
lines changed

3 files changed

+15
-3
lines changed

doc/source/whatsnew/v0.25.1.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ Categorical
3232
Datetimelike
3333
^^^^^^^^^^^^
3434
- Bug in :func:`to_datetime` where passing a timezone-naive :class:`DatetimeArray` or :class:`DatetimeIndex` and ``utc=True`` would incorrectly return a timezone-naive result (:issue:`27733`)
35-
-
35+
- Bug in :func:`maybe_cast_to_datetime` where converting a `np.datetime64` to `datetime64[D]` raise `TypeError` (:issue: `27395`)
3636
-
3737
-
3838

pandas/core/dtypes/cast.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1026,7 +1026,7 @@ def maybe_cast_to_datetime(value, dtype, errors="raise"):
10261026
)
10271027

10281028
if is_datetime64 and not is_dtype_equal(dtype, _NS_DTYPE):
1029-
if dtype.name in ("datetime64", "datetime64[ns]"):
1029+
if dtype.name in ("datetime64", "datetime64[ns]", "datetime64[D]"):
10301030
if dtype.name == "datetime64":
10311031
raise ValueError(msg.format(dtype=dtype.name))
10321032
dtype = _NS_DTYPE
@@ -1044,7 +1044,7 @@ def maybe_cast_to_datetime(value, dtype, errors="raise"):
10441044
value = [value]
10451045

10461046
elif is_timedelta64 and not is_dtype_equal(dtype, _TD_DTYPE):
1047-
if dtype.name in ("timedelta64", "timedelta64[ns]"):
1047+
if dtype.name in ("timedelta64", "timedelta64[ns]", "timedelta64[D]"):
10481048
if dtype.name == "timedelta64":
10491049
raise ValueError(msg.format(dtype=dtype.name))
10501050
dtype = _TD_DTYPE

pandas/tests/dtypes/cast/test_infer_dtype.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
from pandas.core.dtypes.cast import (
77
cast_scalar_to_array,
8+
maybe_cast_to_datetime,
89
infer_dtype_from_array,
910
infer_dtype_from_scalar,
1011
)
@@ -169,3 +170,14 @@ def test_cast_scalar_to_array(obj, dtype):
169170

170171
arr = cast_scalar_to_array(shape, obj, dtype=dtype)
171172
tm.assert_numpy_array_equal(arr, exp)
173+
174+
175+
@pytest.mark.parametrize(
176+
"obj,dtype",
177+
[
178+
(np.datetime64("2017-01-01 01:00:00"), "datetime64[D]"),
179+
(np.datetime64("2017-01-01 02:00:00"), "datetime64[D]"),
180+
],
181+
)
182+
def test_maybe_cast_to_datetime(obj, dtype):
183+
maybe_cast_to_datetime(obj, dtype)

0 commit comments

Comments
 (0)