{"record":{"id":"5e838e81d5cc6134","repo":"pandas-dev/pandas","slug":"cannot-cast-type-self-name-to-dtype-dtype","errorCode":null,"errorMessage":"Cannot cast {type(self).__name__} to dtype {dtype}","messagePattern":"Cannot cast (.+?) to dtype (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/datetimelike.py","lineNumber":461,"sourceCode":"            return super().astype(dtype, copy=copy)\n        elif dtype.kind in \"iu\":\n            # we deliberately ignore int32 vs. int64 here.\n            # See https://github.com/pandas-dev/pandas/issues/24381 for more.\n            values = self.asi8\n            if dtype != np.int64:\n                raise TypeError(\n                    f\"Converting from {self.dtype} to {dtype} is not supported. \"\n                    \"Do obj.astype('int64').astype(dtype) instead\"\n                )\n\n            if copy:\n                values = values.copy()\n            return values\n        elif (dtype.kind in \"mM\" and self.dtype != dtype) or dtype.kind == \"f\":\n            # disallow conversion between datetime/timedelta,\n            # and conversions for any datetimelike to float\n            msg = f\"Cannot cast {type(self).__name__} to dtype {dtype}\"\n            raise TypeError(msg)\n        else:\n            return np.asarray(self, dtype=dtype)\n\n    @overload  # type: ignore[override]\n    def view(self) -> Self: ...\n\n    @overload\n    def view(self, dtype: Literal[\"M8[ns]\"]) -> DatetimeArray: ...\n\n    @overload\n    def view(self, dtype: Literal[\"m8[ns]\"]) -> TimedeltaArray: ...\n\n    @overload\n    def view(self, dtype: Dtype | None = ...) -> ArrayLike: ...\n\n    def view(self, dtype: Dtype | None = None) -> ArrayLike:\n        # we need to explicitly call super() method as long as the `@overload`s\n        #  are present in this file.","sourceCodeStart":443,"sourceCodeEnd":479,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/datetimelike.py#L443-L479","documentation":"Raised by DatetimeLikeArrayMixin.astype when casting to a different datetime/timedelta dtype (e.g. datetime64 to timedelta64) or to any float dtype. These conversions are semantically invalid (datetime to float loses meaning; mixing datetime and timedelta types is undefined), so pandas rejects them outright rather than producing a silently-wrong result. Period arrays also pass through this branch.","triggerScenarios":"datetime_array.astype('float64'), .astype('timedelta64[ns]') on a datetime array, .astype(np.float32) on a TimedeltaIndex, or attempting .astype('datetime64[ns]') on a timedelta array.","commonSituations":"Confusing timestamp and duration semantics; trying to scale nanosecond ticks via float for normalization; or generic dtype-coercion loops over mixed columns.","solutions":["For raw ticks, use .view('int64') then .astype(float) explicitly if you accept the semantics.","For datetime<->timedelta conversion, use arithmetic (e.g. ts - epoch) instead of astype.","For unit conversion, use .as_unit(...) (pandas>=2) rather than astype to another datetime dtype."],"exampleFix":"// before\nts = pd.date_range('2020', periods=3)\nts.astype('float64')  # TypeError: Cannot cast DatetimeArray to dtype float64\n\n// after\nts.values.astype('datetime64[ns]').view('int64').astype('float64')","handlingStrategy":"validation","validationCode":"import numpy as np\ndef to_numeric_ticks(arr):\n    return arr.view('int64').astype('float64')","typeGuard":"import numpy as np\nfrom typing import Any\n\ndef is_castable_dtype(arr: Any, target: Any) -> bool:\n    t = np.dtype(target)\n    return t.kind not in ('f',) and not (t.kind in 'mM' and t != arr.dtype)","tryCatchPattern":"try:\n    arr.astype(target)\nexcept TypeError as e:\n    if 'Cannot cast' in str(e) and 'to dtype' in str(e):\n        arr.view('int64').astype(target)\n    else:\n        raise","preventionTips":["Use .view('int64') for raw ticks instead of astype to float.","Use arithmetic, not astype, for datetime<->timedelta conversion."],"tags":["datetime","astype","float"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}