pandas-dev/pandas · error · TypeError

value should be a '{self._scalar_type.__name__}', 'NaT', or

Error message

value should be a '{self._scalar_type.__name__}', 'NaT', or array of those. Got {msg_got} instead.

What it means

Raised by _validate_listlike when assigning a list-like whose dtype is not recognised as compatible with the array's dtype (and the allow_object escape hatch is off). This is the list-like counterpart of 236/238: a whole array/Series of the wrong dtype (e.g. float64 array set into a datetime array, or int array into a period array) is rejected. The message includes 'or array of those' to indicate list-like inputs are allowed if correctly typed.

Source

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

                # TODO: Could use from_sequence_of_strings if implemented
                # Note: passing dtype is necessary for PeriodArray tests
                value = type(self)._from_sequence(value, dtype=self.dtype)
            except ValueError:
                pass

        if isinstance(value.dtype, CategoricalDtype):
            # e.g. we have a Categorical holding self.dtype
            if value.categories.dtype == self.dtype:
                # TODO: do we need equal dtype or just comparable?
                value = value._internal_get_values()
                value = extract_array(value, extract_numpy=True)

        if allow_object and is_object_dtype(value.dtype):
            pass

        elif not type(self)._is_recognized_dtype(value.dtype):
            msg = self._validation_error_message(value, True)
            raise TypeError(msg)

        if self.dtype.kind in "mM" and not allow_object:
            # error: "DatetimeLikeArrayMixin" has no attribute "as_unit"
            value = value.as_unit(self.unit, round_ok=False)  # type: ignore[attr-defined]
        return value

    def _validate_setitem_value(self, value):
        if is_list_like(value):
            value = self._validate_listlike(value)
        else:
            return self._validate_scalar(value, allow_listlike=True)

        return self._unbox(value)

    @final
    def _unbox(self, other) -> np.int64 | np.datetime64 | np.timedelta64 | np.ndarray:
        """
        Unbox either a scalar with _unbox_scalar or an instance of our own type.

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Convert the list-like to the matching dtype first: pd.to_datetime(series), pd.to_timedelta(series), or .astype(self.dtype).
  2. Build a same-type array with type(self)._from_sequence(values, dtype=self.dtype).
  3. Validate value.dtype with type(self)._is_recognized_dtype(value.dtype) before assignment.

Example fix

// before
arr = pd.date_range('2020', periods=3)._data
arr[:] = [1, 2, 3]  # TypeError: value should be 'Timestamp','NaT',or array of those

// after
arr[:] = pd.to_datetime(['2020-01-01','2020-01-02','2020-01-03'])
Defensive patterns

Strategy: validation

Validate before calling

import pandas as pd
def coerce_listlike_for(arr, values):
    cls = type(arr)
    if not cls._is_recognized_dtype(getattr(values, 'dtype', None)):
        return cls._from_sequence(values, dtype=arr.dtype)
    return values

Type guard

import pandas as pd
from typing import Any

def is_recognized_listlike(arr: Any, values: Any) -> bool:
    dt = getattr(values, 'dtype', None)
    return dt is not None and type(arr)._is_recognized_dtype(dt)

Try / catch

try:
    arr[:] = values
except TypeError as e:
    if 'or array of those' in str(e):
        cls = type(arr)
        arr[:] = cls._from_sequence(values, dtype=arr.dtype)
    else:
        raise

Prevention

When it happens

Trigger: arr[:] = np.array([1.0, 2.0, 3.0]) on a DatetimeArray; setting a categorical-of-float into a datetime array; fillna with an int array; setitem with a Series whose dtype is incompatible.

Common situations: Bulk assignment from a numeric column into a datetime column; loading data where the source column dtype differs from the target; vectorised fill operations with the wrong-typed filler.

Related errors


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