pandas-dev/pandas · error · TypeError

dtype cannot be converted to timedelta64[ns]

Error message

dtype {data.dtype} cannot be converted to timedelta64[ns]

What it means

Raised in the internal conversion path (the `_td64`-style helper in timedeltas.py) when `data` has a dtype that is neither integer-backed, timedelta64, nor a supported timedelta resolution. The branch explicitly notes datetime64 is included (GH#23539, GH#29794): you cannot reinterpret datetime64 data as timedelta64. The error names the offending dtype so the caller can correct the input.

Solutions

  1. Convert the data with `pd.to_timedelta(...)` before constructing the timedelta array.
  2. If you hold datetime64 data and need durations, subtract a reference Timestamp to obtain a timedelta64 result rather than re-viewing.
  3. Validate the input dtype and branch to the correct constructor.

Example fix

# before
pd.TimedeltaIndex(np.array(['2020-01-01'], dtype='datetime64[ns]'))  # TypeError

# after
ref = pd.Timestamp('2020-01-01')
pd.to_timedelta((pd.to_datetime(['2020-01-01']) - ref).total_seconds(), unit='s')
Defensive patterns

Strategy: type-guard

Validate before calling

import numpy as np

def is_timedelta_convertible(data) -> bool:
    arr = np.asarray(data)
    k = arr.dtype.kind
    # integer, supported timedelta64, or convertible via to_timedelta
    return k in 'iu' or (k == 'm' and arr.dtype != 'datetime64')

Type guard

import numpy as np

def is_not_datetime_or_object(arr) -> bool:
    return getattr(arr, 'dtype', None) is not None and arr.dtype.kind not in ('M', 'O', 'U', 'S')

Try / catch

try:
    tdi = pd.TimedeltaIndex(data)
except TypeError as e:
    if 'cannot be converted to timedelta64' in str(e):
        tdi = pd.to_timedelta(pd.to_numeric(pd.Series(data)), unit='ns')
    else:
        raise

Prevention

When it happens

Trigger: Passing a datetime64 array/Series into a constructor expecting timedelta64; providing float, object, or string dtype data without prior conversion to timedelta.

Common situations: Confusing Timestamp and Timedelta columns during data prep; assuming a dtype view will silently reinterpret datetime data.

Related errors


AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11). Data as JSON: /api/errors/49ada9b06b661b76. Report an issue: GitHub.

Appendix: source

Thrown at pandas/core/arrays/timedeltas.py:1328

        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.

    Parameters

View on GitHub (pinned to 3b7651241d)