pandas-dev/pandas · error · TypeError

cannot add {type(self).__name__} and {type(other).__name__}

Error message

cannot add {type(self).__name__} and {type(other).__name__}

What it means

Raised by _add_datetimelike_scalar when a datelike scalar (datetime/Timestamp/np.datetime64) is added to an array whose dtype is not timedelta (kind != 'm'). The rule is that TimedeltaArray + datetime -> DatetimeArray is well-defined, but DatetimeArray + datetime or PeriodArray + datetime is not; pandas refuses rather than guess.

Source

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

        """
        Get the int64 values and b_mask to pass to add_overflowsafe.
        """
        if isinstance(other, Period):
            i8values = other.ordinal
            mask = None
        elif isinstance(other, (Timestamp, Timedelta)):
            i8values = other._value
            mask = None
        else:
            # PeriodArray, DatetimeArray, TimedeltaArray
            mask = other._isnan
            i8values = other.asi8
        return i8values, mask

    @final
    def _add_datetimelike_scalar(self, other) -> DatetimeArray:
        if not lib.is_np_dtype(self.dtype, "m"):
            raise TypeError(
                f"cannot add {type(self).__name__} and {type(other).__name__}"
            )

        self = cast("TimedeltaArray", self)

        from pandas.core.arrays import DatetimeArray
        from pandas.core.arrays.datetimes import tz_to_dtype

        assert other is not NaT
        if isna(other):
            # i.e. np.datetime64("NaT")
            # In this case we specifically interpret NaT as a datetime, not
            # the timedelta interpretation we would get by returning self + NaT
            result = self._ndarray + NaT.to_datetime64().astype(f"M8[{self.unit}]")
            # Preserve our resolution
            return DatetimeArray._simple_new(result, dtype=result.dtype)

        other = Timestamp(other)

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Replace the datetime operand with a Timedelta: idx + pd.Timedelta(days=1) instead of idx + pd.Timestamp(...).
  2. If you meant to broadcast a base timestamp, compute (idx - base_ts) to get a TimedeltaIndex, or use Timestamp arithmetic elementwise.
  3. Subtract the datetime scalar from each element explicitly via idx.__sub__ if a timedelta result was intended.
  4. Check idx.dtype.kind before the op: timedelta ('m') supports datetime addition, datetime ('M') and Period do not.

Example fix

// before
idx = pd.date_range('2020-01-01', periods=3)
out = idx + pd.Timestamp('2020-01-01')  # TypeError: cannot add DatetimeArray and Timestamp
// after
out = idx + pd.Timedelta(days=1)
Defensive patterns

Strategy: type-guard

Validate before calling

from pandas.api.types import is_timedelta64_dtype
if not is_timedelta64_dtype(idx):
    # adding a datetime scalar is invalid; convert to Timedelta
    other = pd.Timedelta(days=1)
out = idx + other

Type guard

def accepts_datetime_addition(idx) -> bool:
    return getattr(idx.dtype, 'kind', None) == 'm'  # only timedelta dtype

Try / catch

try:
    out = idx + ts
except TypeError as e:
    if 'cannot add' in str(e) and 'Timestamp' in str(e):
        out = idx + pd.Timedelta(ts - pd.Timestamp(0))
    else:
        raise

Prevention

When it happens

Trigger: DatetimeIndex + datetime scalar (e.g. idx + pd.Timestamp('2020-01-01')), or PeriodIndex + datetime, dispatched through __add__ at line 1324 into _add_datetimelike_scalar at line 1045, which hits the guard at 1046. Also triggered by reversed ops via __radd__.

Common situations: Confusing datetime+datetime with datetime+timedelta arithmetic; forgetting to wrap a date column in pd.Timedelta; data ingestion that stored offsets as datetime instead of timedelta.

Related errors


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