pandas-dev/pandas · error · TypeError
dtype {data.dtype} cannot be converted to timedelta64[ns]
Error message
dtype {data.dtype} cannot be converted to timedelta64[ns] What it means
Raised by sequence_to_td64ns when data.dtype is not integer, float, object, or timedelta64. The else-branch explicitly lists datetime64 as a known trigger (GH#23539, GH#29794): you cannot convert a datetime array into a timedelta array directly.
Source
Thrown at pandas/core/arrays/timedeltas.py:1308
data = data.astype(np.float64, copy=False)
try:
data = cast_from_unit_vectorized(data, unit or "ns")
except OutOfBoundsDatetime as err:
raise OutOfBoundsTimedelta(*err.args) from err
data[mask] = iNaT
data = data.view("m8[ns]")
copy = False
elif lib.is_np_dtype(data.dtype, "m"):
if not is_supported_dtype(data.dtype):
# cast to closest supported unit, i.e. s or ns
new_dtype = get_supported_dtype(data.dtype)
data = astype_overflowsafe(data, dtype=new_dtype, copy=False)
copy = False
else:
# This includes datetime64-dtype, see GH#23539, GH#29794
raise TypeError(f"dtype {data.dtype} cannot be converted to timedelta64[ns]")
if not copy:
data = np.asarray(data)
else:
data = np.array(data, copy=copy)
assert data.dtype.kind == "m"
assert data.dtype != "m8" # i.e. not unit-less
return data
def _ints_to_td64ns(data, unit: str = "ns") -> tuple[np.ndarray, bool]:
"""
Convert an ndarray with integer-dtype to timedelta64[ns] dtype, treating
the integers as multiples of the given timedelta unit.
ParametersView on GitHub (pinned to 71959b8cb9)
Solutions
- If you have datetimes, compute differences: `dt_a - dt_b` already yields timedelta.
- Cast object columns of strings first via pd.to_timedelta on the raw strings.
- Check data.dtype before calling to_timedelta and branch accordingly.
Example fix
// before s = pd.to_timedelta(df['timestamp']) # datetime64 // after s = df['timestamp'] - df['timestamp'].min() # timedelta
Defensive patterns
Strategy: type-guard
Validate before calling
import numpy as np
if np.asarray(data).dtype.kind == 'M':
raise TypeError('input is datetime64; compute differences to get timedelta') Type guard
def is_timedelta_convertible(data) -> bool:
import numpy as np
k = np.asarray(data).dtype.kind
return k in 'iufOM' or k == 'm' Try / catch
try:
s = pd.to_timedelta(data)
except TypeError as e:
if 'cannot be converted to timedelta64' in str(e):
s = data - np.min(data) # convert datetime to timedelta via diff
else:
raise Prevention
- Branch on dtype.kind before conversion.
- Subtract datetimes to get timedeltas.
- Audit column types at ingestion.
When it happens
Trigger: `pd.to_timedelta(pd.to_datetime(['2020-01-01']))`, or passing a datetime64 ndarray / complex-dtype array to to_timedelta / TimedeltaIndex constructor.
Common situations: Confusing duration vs timestamp; subtracting two datetimes but forgetting to wrap with subtraction that yields timedelta; passing the wrong column from a pipeline.
Related errors
- overflow in timedelta operation
- cannot add {type(self).__name__} and {type(other).__name__}
- cannot subtract a datelike from a {type(self).__name__}
- Supported units are 's', 'ms', 'us', 'ns'
- {dtype=} does not have a resolution.
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/49ada9b06b661b76.
Report an issue: GitHub.