{"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/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/datetimelike.py#L443-L479","documentation":"Raised in DatetimeLikeArray.astype when converting a datetimelike array to a float dtype, or when converting between datetime and timedelta kinds (e.g., datetime64 to timedelta64). Floats cannot represent datetimelike ticks without losing the unit semantics, and cross-kind conversions (datetime<->timedelta) are nonsensical, so both are rejected.","triggerScenarios":"dti.astype('float64'), tdi.astype(np.float32'), dti.astype('timedelta64[ns]'), tdi.astype('datetime64[ns]'). Period values cast to float. Converting a datetime column to float for legacy serialization.","commonSituations":"User expects astype('float') to yield epoch seconds — it does not; use .view or division by the unit. Cross-kind cast after a wrong df.astype({...}) mapping. Migration code that previously used .values.astype(float).","solutions":["For epoch values: dti.view('int64') or (dti - epoch) // pd.Timedelta('1s') for seconds.","For timedelta as numeric seconds: tdi.total_seconds() (on TimedeltaIndex) or tdi.view('int64') / 1e9.","To reinterpret datetime64 bits as timedelta64 (rare): use .view('timedelta64[ns]') not .astype.","Keep datetimelike data in its native dtype; convert to int64 first if a numeric form is truly needed."],"exampleFix":"# before\ndti.astype('float64')  # TypeError\n\n# after\n(dti.view('int64') / 1e9)  # epoch seconds as float","handlingStrategy":"validation","validationCode":"import numpy as np\nif dtype.kind in 'fc' or (dtype.kind in 'mM' and dti.dtype != dtype):\n    raise TypeError(f'Cannot cast {dti.dtype} to {dtype}; use .view or numeric conversion')\ndti.astype(dtype)","typeGuard":"def castable_from_datetimelike(src_dtype, target_dtype) -> bool:\n    import numpy as np\n    if target_dtype.kind == 'f':\n        return False\n    if target_dtype.kind in 'mM' and src_dtype != target_dtype:\n        return False\n    return True","tryCatchPattern":"try:\n    dti.astype('float64')\nexcept TypeError as e:\n    if 'Cannot cast' in str(e):\n        dti.view('int64') / 1e9\n    else:\n        raise","preventionTips":["Convert datetimelike to int64 ticks before producing float epoch values.","Never astype datetimelike directly to float; use division or .view."],"tags":["datetimelike","astype","float-conversion","cross-kind"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}