{"record":{"id":"d7079e2808034955","repo":"pandas-dev/pandas","slug":"dtype-data-dtype-cannot-be-converted-to-datetime","errorCode":null,"errorMessage":"dtype {data.dtype} cannot be converted to datetime64[ns]","messagePattern":"dtype (.+?) cannot be converted to datetime64\\[ns\\]","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/datetimes.py","lineNumber":2901,"sourceCode":"    Raises\n    ------\n    TypeError : PeriodDType data is passed\n    \"\"\"\n    if not hasattr(data, \"dtype\"):\n        # e.g. collections.deque\n        return data, copy\n\n    if is_float_dtype(data.dtype):\n        # pre-2.0 we treated these as wall-times, inconsistent with ints\n        # GH#23675, GH#45573 deprecated to treat symmetrically with integer dtypes.\n        # Note: data.astype(np.int64) fails ARM tests, see\n        # https://github.com/pandas-dev/pandas/issues/49468.\n        data = data.astype(DT64NS_DTYPE).view(\"i8\")\n        copy = False\n\n    elif lib.is_np_dtype(data.dtype, \"m\") or is_bool_dtype(data.dtype):\n        # GH#29794 enforcing deprecation introduced in GH#23539\n        raise TypeError(f\"dtype {data.dtype} cannot be converted to datetime64[ns]\")\n    elif isinstance(data.dtype, PeriodDtype):\n        # Note: without explicitly raising here, PeriodIndex\n        #  test_setops.test_join_does_not_recur fails\n        raise TypeError(\n            \"Passing PeriodDtype data is invalid. Use `data.to_timestamp()` instead\"\n        )\n\n    elif isinstance(data.dtype, ExtensionDtype) and not isinstance(\n        data.dtype, DatetimeTZDtype\n    ):\n        # TODO: We have no tests for these\n        data = np.array(data, dtype=np.object_)\n        copy = False\n\n    return data, copy\n\n\n# -------------------------------------------------------------------","sourceCodeStart":2883,"sourceCodeEnd":2919,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/datetimes.py#L2883-L2919","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Use the correct constructor: `pd.to_timedelta(s)` for durations, `pd.to_datetime(s)` only for actual datetime-like input.","If the timedelta represents an offset from a reference epoch, add it explicitly: `pd.Timestamp('1970-01-01') + s`.","Convert booleans to a meaningful representation first (e.g. map True/False to specific timestamps) before constructing a datetime.","Audit the upstream computation: identify where timedelta/bool was produced and fix the wrong branch."],"exampleFix":"// before\ns = pd.to_datetime(df['elapsed'])  # df['elapsed'] is timedelta64\n\n// after\ns = pd.Timestamp('1970-01-01') + df['elapsed']","handlingStrategy":"type-guard","validationCode":"import pandas as pd, numpy as np\n\ndef to_datetime_safe(s):\n    if pd.api.types.is_timedelta64_dtype(s):\n        raise TypeError('Input is timedelta; add to an epoch instead')\n    if pd.api.types.is_bool_dtype(s):\n        raise TypeError('Input is bool; map to explicit timestamps first')\n    return pd.to_datetime(s)","typeGuard":"def is_datetime_compatible(s) -> bool:\n    import pandas as pd\n    return not (pd.api.types.is_timedelta64_dtype(s) or pd.api.types.is_bool_dtype(s))","tryCatchPattern":"try:\n    out = pd.to_datetime(s)\nexcept TypeError as e:\n    if 'cannot be converted to datetime64' in str(e):\n        raise TypeError(f'Refuse to coerce non-datetime dtype: {s.dtype}') from e\n    raise","preventionTips":["Check dtype before calling to_datetime.","Do not feed timedelta/bool columns into datetime constructors."],"tags":["datetime","dtype","timedelta","bool","to-datetime"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}