{"record":{"id":"7a389fa63e5a7244","repo":"pandas-dev/pandas","slug":"converting-from-self-dtype-to-dtype-is-not-sup","errorCode":null,"errorMessage":"Converting from {self.dtype} to {dtype} is not supported. Do obj.astype('int64').astype(dtype) instead","messagePattern":"Converting from (.+?) to (.+?) is not supported\\. Do obj\\.astype\\('int64'\\)\\.astype\\(dtype\\) instead","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/datetimelike.py","lineNumber":449,"sourceCode":"\n            return self._box_values(self.asi8.ravel()).reshape(self.shape)\n\n        elif is_string_dtype(dtype):\n            if isinstance(dtype, ExtensionDtype):\n                arr_object = self._format_native_types(na_rep=dtype.na_value)  # type: ignore[arg-type]\n                cls = dtype.construct_array_type()\n                return cls._from_sequence(arr_object, dtype=dtype, copy=False)\n            else:\n                return self._format_native_types()\n\n        elif isinstance(dtype, ExtensionDtype):\n            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","sourceCodeStart":431,"sourceCodeEnd":467,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/datetimelike.py#L431-L467","documentation":"Raised by DatetimeLikeArrayMixin.astype when converting a datetime/timedelta/period array to an integer dtype other than int64. Internally the array is stored as int64 nanosecond ticks; converting to int32/uint/intp would silently truncate or change meaning, so only int64 is allowed directly and other integer widths must go through an explicit int64 step. The message itself tells you the workaround.","triggerScenarios":"arr.astype('int32'), .astype(np.uint32), .astype('Int32') on a DatetimeIndex/TimedeltaIndex/PeriodIndex/their arrays.","commonSituations":"Downcasting nanosecond ticks to save memory, interfacing with systems expecting 32-bit timestamps, or building feature columns from timestamps.","solutions":["Follow the message: arr.astype('int64').astype(target_int_dtype) to make the truncation explicit.","Use .view('int64') if you want raw ticks without conversion semantics.","Reconsider whether 32-bit storage is safe for your nanosecond-range data (it usually is not)."],"exampleFix":"// before\nidx = pd.date_range('2020', periods=3)\nidx.astype('int32')  # TypeError\n\n// after\nidx.astype('int64').astype('int32')","handlingStrategy":"validation","validationCode":"import numpy as np\ndef to_int_dtype(arr, target):\n    if target != np.dtype('int64'):\n        return arr.astype('int64').astype(target)\n    return arr.astype(target)","typeGuard":"import numpy as np\nfrom typing import Any\n\ndef is_direct_int64_castable(arr: Any, target: Any) -> bool:\n    return np.dtype(target) == np.dtype('int64')","tryCatchPattern":"try:\n    arr.astype(target_int)\nexcept TypeError as e:\n    if 'Do obj.astype' in str(e):\n        arr.astype('int64').astype(target_int)\n    else:\n        raise","preventionTips":["Always go through int64 when downcasting datetime ticks.","Be aware int32 cannot hold nanosecond ticks for modern dates."],"tags":["datetime","astype","integer"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}