Skip to content

Commit a31e739

Browse files
authored
COMPAT: make astype to datetime/timedelta types more robust (#19176)
closes #19116
1 parent 982e112 commit a31e739

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

pandas/core/dtypes/cast.py

+14-1
Original file line numberDiff line numberDiff line change
@@ -690,7 +690,7 @@ def astype_nansafe(arr, dtype, copy=True):
690690
raise ValueError('Cannot convert non-finite values (NA or inf) to '
691691
'integer')
692692

693-
elif arr.dtype == np.object_ and np.issubdtype(dtype.type, np.integer):
693+
elif is_object_dtype(arr.dtype) and np.issubdtype(dtype.type, np.integer):
694694
# work around NumPy brokenness, #1987
695695
return lib.astype_intsafe(arr.ravel(), dtype).reshape(arr.shape)
696696

@@ -703,6 +703,19 @@ def astype_nansafe(arr, dtype, copy=True):
703703
dtype = np.dtype(dtype.name + "[ns]")
704704

705705
if copy:
706+
707+
if arr.dtype == dtype:
708+
return arr.copy()
709+
710+
# we handle datetimelikes with pandas machinery
711+
# to be robust to the input type
712+
elif is_datetime64_dtype(dtype):
713+
from pandas import to_datetime
714+
return to_datetime(arr).values
715+
elif is_timedelta64_dtype(dtype):
716+
from pandas import to_timedelta
717+
return to_timedelta(arr).values
718+
706719
return arr.astype(dtype)
707720
return arr.view(dtype)
708721

pandas/tests/io/json/test_json_table_schema.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -499,7 +499,7 @@ def test_read_json_table_orient(self, index_nm, vals):
499499
tm.assert_frame_equal(df, result)
500500

501501
@pytest.mark.parametrize("index_nm", [
502-
None, "idx", pytest.param("index", marks=pytest.mark.xfail)])
502+
None, "idx", "index"])
503503
@pytest.mark.parametrize("vals", [
504504
{'timedeltas': pd.timedelta_range('1H', periods=4, freq='T')},
505505
{'timezones': pd.date_range('2016-01-01', freq='d', periods=4,

0 commit comments

Comments
 (0)