|
43 | 43 | iNaT,
|
44 | 44 | ints_to_pydatetime,
|
45 | 45 | )
|
| 46 | +from pandas._libs.tslibs.timedeltas import array_to_timedelta64 |
46 | 47 | from pandas._typing import (
|
47 | 48 | AnyArrayLike,
|
48 | 49 | ArrayLike,
|
@@ -1459,14 +1460,15 @@ def try_timedelta(v: np.ndarray) -> np.ndarray:
|
1459 | 1460 | # safe coerce to timedelta64
|
1460 | 1461 |
|
1461 | 1462 | # will try first with a string & object conversion
|
1462 |
| - from pandas import to_timedelta |
1463 |
| - |
1464 | 1463 | 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]") |
1466 | 1468 | except (ValueError, OverflowError):
|
1467 | 1469 | return v.reshape(shape)
|
1468 | 1470 | else:
|
1469 |
| - return np.asarray(td_values).reshape(shape) |
| 1471 | + return td_values.reshape(shape) |
1470 | 1472 |
|
1471 | 1473 | inferred_type = lib.infer_datetimelike_array(ensure_object(v))
|
1472 | 1474 |
|
@@ -1500,8 +1502,8 @@ def maybe_cast_to_datetime(
|
1500 | 1502 | try to cast the array/value to a datetimelike dtype, converting float
|
1501 | 1503 | nan to iNaT
|
1502 | 1504 | """
|
| 1505 | + from pandas.core.arrays.timedeltas import sequence_to_td64ns |
1503 | 1506 | from pandas.core.tools.datetimes import to_datetime
|
1504 |
| - from pandas.core.tools.timedeltas import to_timedelta |
1505 | 1507 |
|
1506 | 1508 | if not is_list_like(value):
|
1507 | 1509 | raise TypeError("value must be listlike")
|
@@ -1582,7 +1584,8 @@ def maybe_cast_to_datetime(
|
1582 | 1584 | # so localize and convert
|
1583 | 1585 | value = dta.tz_localize("UTC").tz_convert(dtype.tz)
|
1584 | 1586 | 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) |
1586 | 1589 | except OutOfBoundsDatetime:
|
1587 | 1590 | raise
|
1588 | 1591 | except ValueError as err:
|
|
0 commit comments