Skip to content

Commit e06ad0a

Browse files
authored
REF: use lower-level casting func instead of to_timedelta (#40155)
1 parent bc0bcae commit e06ad0a

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

pandas/core/dtypes/cast.py

+9-6
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
iNaT,
4444
ints_to_pydatetime,
4545
)
46+
from pandas._libs.tslibs.timedeltas import array_to_timedelta64
4647
from pandas._typing import (
4748
AnyArrayLike,
4849
ArrayLike,
@@ -1459,14 +1460,15 @@ def try_timedelta(v: np.ndarray) -> np.ndarray:
14591460
# safe coerce to timedelta64
14601461

14611462
# will try first with a string & object conversion
1462-
from pandas import to_timedelta
1463-
14641463
try:
1465-
td_values = to_timedelta(v)
1464+
# bc we know v.dtype == object, this is equivalent to
1465+
# `np.asarray(to_timedelta(v))`, but using a lower-level API that
1466+
# does not require a circular import.
1467+
td_values = array_to_timedelta64(v).view("m8[ns]")
14661468
except (ValueError, OverflowError):
14671469
return v.reshape(shape)
14681470
else:
1469-
return np.asarray(td_values).reshape(shape)
1471+
return td_values.reshape(shape)
14701472

14711473
inferred_type = lib.infer_datetimelike_array(ensure_object(v))
14721474

@@ -1500,8 +1502,8 @@ def maybe_cast_to_datetime(
15001502
try to cast the array/value to a datetimelike dtype, converting float
15011503
nan to iNaT
15021504
"""
1505+
from pandas.core.arrays.timedeltas import sequence_to_td64ns
15031506
from pandas.core.tools.datetimes import to_datetime
1504-
from pandas.core.tools.timedeltas import to_timedelta
15051507

15061508
if not is_list_like(value):
15071509
raise TypeError("value must be listlike")
@@ -1582,7 +1584,8 @@ def maybe_cast_to_datetime(
15821584
# so localize and convert
15831585
value = dta.tz_localize("UTC").tz_convert(dtype.tz)
15841586
elif is_timedelta64:
1585-
value = to_timedelta(value, errors="raise")._values
1587+
# if successful, we get a ndarray[td64ns]
1588+
value, _ = sequence_to_td64ns(value)
15861589
except OutOfBoundsDatetime:
15871590
raise
15881591
except ValueError as err:

0 commit comments

Comments
 (0)