{"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/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/datetimelike.py#L431-L467","documentation":"Raised in DatetimeLikeArray.astype when converting to an integer dtype other than int64. Datetimelike values are stored as int64 nanosecond (or unit-specific) ticks; converting to int32/int16/int8 would silently overflow or lose precision for typical timestamps. pandas deliberately refuses and tells the user to round-trip through int64 explicitly so the truncation is intentional.","triggerScenarios":"dti.astype('int32'), tdi.astype(np.int16'), period_index.astype('int8'). df['ts'].astype('int32'). Converting a datetime column for a fixed-width binary format that expects int32.","commonSituations":"User wants compact storage of epoch seconds in int32 and calls astype directly. Interop with systems expecting 32-bit Unix timestamps. Building features for ML with reduced precision integers.","solutions":["Two-step cast as the message suggests: obj.astype('int64').astype('int32').","For epoch seconds: (dti.view('int64') // 10**9).astype('int32') — explicit truncation.","Use int64 if precision/range matters; int32 overflows for dates beyond 2038-01-19.","Consider .view(np.int32) on the underlying array if you genuinely want the raw 32-bit reinterpretation (semantics differ)."],"exampleFix":"# before\ndti.astype('int32')  # TypeError\n\n# after\ndti.astype('int64').astype('int32')","handlingStrategy":"validation","validationCode":"target = np.int32\nout = dti.astype('int64')\nif target != np.int64:\n    out = out.astype(target)","typeGuard":"def needs_two_step_int_cast(target) -> bool:\n    import numpy as np\n    return np.issubdtype(target, np.integer) and target != np.int64","tryCatchPattern":"try:\n    dti.astype('int32')\nexcept TypeError as e:\n    if 'not supported' in str(e):\n        dti.astype('int64').astype('int32')\n    else:\n        raise","preventionTips":["Always cast datetimelike to int64 first, then narrow if required.","Check Y2038 implications before choosing int32 for timestamps."],"tags":["datetimelike","astype","int-conversion","precision"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}