pandas-dev/pandas · error · TypeError

dtype cannot be converted to datetime64[ns]

Error message

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

What it means

Raised by maybe_convert_dtype when the input data is timedelta dtype ('m') or bool dtype — neither is meaningfully convertible to datetime64[ns]. GH#29794/GH#23539 turned the prior silent/depcrecated behavior into a hard error. Floats and ints are still accepted (treated as nanoseconds since epoch); timedeltas and bools are not.

Solutions

  1. Use the correct constructor: `pd.to_timedelta(s)` for durations, `pd.to_datetime(s)` only for actual datetime-like input.
  2. If the timedelta represents an offset from a reference epoch, add it explicitly: `pd.Timestamp('1970-01-01') + s`.
  3. Convert booleans to a meaningful representation first (e.g. map True/False to specific timestamps) before constructing a datetime.
  4. Audit the upstream computation: identify where timedelta/bool was produced and fix the wrong branch.

Example fix

// before
s = pd.to_datetime(df['elapsed'])  # df['elapsed'] is timedelta64

// after
s = pd.Timestamp('1970-01-01') + df['elapsed']
Defensive patterns

Strategy: type-guard

Validate before calling

import pandas as pd, numpy as np

def to_datetime_safe(s):
    if pd.api.types.is_timedelta64_dtype(s):
        raise TypeError('Input is timedelta; add to an epoch instead')
    if pd.api.types.is_bool_dtype(s):
        raise TypeError('Input is bool; map to explicit timestamps first')
    return pd.to_datetime(s)

Type guard

def is_datetime_compatible(s) -> bool:
    import pandas as pd
    return not (pd.api.types.is_timedelta64_dtype(s) or pd.api.types.is_bool_dtype(s))

Try / catch

try:
    out = pd.to_datetime(s)
except TypeError as e:
    if 'cannot be converted to datetime64' in str(e):
        raise TypeError(f'Refuse to coerce non-datetime dtype: {s.dtype}') from e
    raise

Prevention

When it happens

Trigger: Passing a Timedelta Series/Index or a boolean Series/Index where a datetime is expected: `pd.to_datetime(timedelta_series)`, `pd.DatetimeIndex(bool_array)`, or assigning a timedelta column into a datetime index. Also reached through DataFrame/Index constructors that route through maybe_convert_dtype.

Common situations: Confusing `pd.to_timedelta` with `pd.to_datetime`. Subtracting two datetimes (which yields a timedelta) then passing that result back into `to_datetime`. Loading a column where booleans were used as presence flags and treating them as dates.

Related errors


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

Appendix: source

Thrown at pandas/core/arrays/datetimes.py:2901

    Raises
    ------
    TypeError : PeriodDType data is passed
    """
    if not hasattr(data, "dtype"):
        # e.g. collections.deque
        return data, copy

    if is_float_dtype(data.dtype):
        # pre-2.0 we treated these as wall-times, inconsistent with ints
        # GH#23675, GH#45573 deprecated to treat symmetrically with integer dtypes.
        # Note: data.astype(np.int64) fails ARM tests, see
        # https://github.com/pandas-dev/pandas/issues/49468.
        data = data.astype(DT64NS_DTYPE).view("i8")
        copy = False

    elif lib.is_np_dtype(data.dtype, "m") or is_bool_dtype(data.dtype):
        # GH#29794 enforcing deprecation introduced in GH#23539
        raise TypeError(f"dtype {data.dtype} cannot be converted to datetime64[ns]")
    elif isinstance(data.dtype, PeriodDtype):
        # Note: without explicitly raising here, PeriodIndex
        #  test_setops.test_join_does_not_recur fails
        raise TypeError(
            "Passing PeriodDtype data is invalid. Use `data.to_timestamp()` instead"
        )

    elif isinstance(data.dtype, ExtensionDtype) and not isinstance(
        data.dtype, DatetimeTZDtype
    ):
        # TODO: We have no tests for these
        data = np.array(data, dtype=np.object_)
        copy = False

    return data, copy


# -------------------------------------------------------------------

View on GitHub (pinned to 3b7651241d)