pandas-dev/pandas · error · TypeError

Converting from {self.dtype} to {dtype} is not supported. Do

Error message

Converting from {self.dtype} to {dtype} is not supported. Do obj.astype('int64').astype(dtype) instead

What it means

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.

Source

Thrown at pandas/core/arrays/datetimelike.py:449

            return self._box_values(self.asi8.ravel()).reshape(self.shape)

        elif is_string_dtype(dtype):
            if isinstance(dtype, ExtensionDtype):
                arr_object = self._format_native_types(na_rep=dtype.na_value)  # type: ignore[arg-type]
                cls = dtype.construct_array_type()
                return cls._from_sequence(arr_object, dtype=dtype, copy=False)
            else:
                return self._format_native_types()

        elif isinstance(dtype, ExtensionDtype):
            return super().astype(dtype, copy=copy)
        elif dtype.kind in "iu":
            # we deliberately ignore int32 vs. int64 here.
            # See https://github.com/pandas-dev/pandas/issues/24381 for more.
            values = self.asi8
            if dtype != np.int64:
                raise TypeError(
                    f"Converting from {self.dtype} to {dtype} is not supported. "
                    "Do obj.astype('int64').astype(dtype) instead"
                )

            if copy:
                values = values.copy()
            return values
        elif (dtype.kind in "mM" and self.dtype != dtype) or dtype.kind == "f":
            # disallow conversion between datetime/timedelta,
            # and conversions for any datetimelike to float
            msg = f"Cannot cast {type(self).__name__} to dtype {dtype}"
            raise TypeError(msg)
        else:
            return np.asarray(self, dtype=dtype)

    @overload  # type: ignore[override]
    def view(self) -> Self: ...

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Follow the message: arr.astype('int64').astype(target_int_dtype) to make the truncation explicit.
  2. Use .view('int64') if you want raw ticks without conversion semantics.
  3. Reconsider whether 32-bit storage is safe for your nanosecond-range data (it usually is not).

Example fix

// before
idx = pd.date_range('2020', periods=3)
idx.astype('int32')  # TypeError

// after
idx.astype('int64').astype('int32')
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np
def to_int_dtype(arr, target):
    if target != np.dtype('int64'):
        return arr.astype('int64').astype(target)
    return arr.astype(target)

Type guard

import numpy as np
from typing import Any

def is_direct_int64_castable(arr: Any, target: Any) -> bool:
    return np.dtype(target) == np.dtype('int64')

Try / catch

try:
    arr.astype(target_int)
except TypeError as e:
    if 'Do obj.astype' in str(e):
        arr.astype('int64').astype(target_int)
    else:
        raise

Prevention

When it happens

Trigger: arr.astype('int32'), .astype(np.uint32), .astype('Int32') on a DatetimeIndex/TimedeltaIndex/PeriodIndex/their arrays.

Common situations: Downcasting nanosecond ticks to save memory, interfacing with systems expecting 32-bit timestamps, or building feature columns from timestamps.

Related errors


AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07). Data as JSON: /api/errors/7a389fa63e5a7244. Report an issue: GitHub.