{"record":{"id":"421af7c50f81d520","repo":"pandas-dev/pandas","slug":"cannot-subtract-type-self-name-from-type-o","errorCode":null,"errorMessage":"cannot subtract {type(self).__name__} from {type(other).__name__}[{other.dtype}]","messagePattern":"cannot subtract (.+?) from (.+?)\\[(.+?)\\]","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/datetimelike.py","lineNumber":1452,"sourceCode":"            other_dtype, DatetimeTZDtype\n        )\n\n        if other_is_dt64 and lib.is_np_dtype(self.dtype, \"m\"):\n            # ndarray[datetime64] cannot be subtracted from self, so\n            # we need to wrap in DatetimeArray/Index and flip the operation\n            if lib.is_scalar(other):\n                # i.e. np.datetime64 object\n                return Timestamp(other) - self\n            if not isinstance(other, DatetimeLikeArrayMixin):\n                # Avoid down-casting DatetimeIndex\n                from pandas.core.arrays import DatetimeArray\n\n                other = DatetimeArray._from_sequence(other, dtype=other.dtype)\n            return other - self\n        elif self.dtype.kind == \"M\" and hasattr(other, \"dtype\") and not other_is_dt64:\n            # GH#19959 datetime - datetime is well-defined as timedelta,\n            # but any other type - datetime is not well-defined.\n            raise TypeError(\n                f\"cannot subtract {type(self).__name__} from \"\n                f\"{type(other).__name__}[{other.dtype}]\"\n            )\n        elif isinstance(self.dtype, PeriodDtype) and lib.is_np_dtype(other_dtype, \"m\"):\n            # TODO: Can we simplify/generalize these cases at all?\n            raise TypeError(f\"cannot subtract {type(self).__name__} from {other.dtype}\")\n        elif lib.is_np_dtype(self.dtype, \"m\"):\n            self = cast(\"TimedeltaArray\", self)\n            return (-self) + other\n\n        flipped = self - other\n        if flipped.dtype.kind == \"M\":\n            # GH#59571 give a more helpful exception message\n            raise TypeError(\n                f\"cannot subtract {type(self).__name__} from {type(other).__name__}\"\n            )\n        # We get here with e.g. datetime objects\n        return -flipped","sourceCodeStart":1434,"sourceCodeEnd":1470,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/datetimelike.py#L1434-L1470","documentation":"Raised by __rsub__ when self.dtype.kind == 'M' (DatetimeArray) and the left operand other has a dtype but is not itself datelike. Reflected subtraction (other - DatetimeArray) is only defined for datelike left operands; anything else (numeric, object) is rejected with a message that includes other's dtype.","triggerScenarios":"np.array([1,2,3]) - datetime_idx, or int_series - DatetimeIndex, dispatched to __rsub__ at line 1431; the branch at line 1449 fires because other_is_dt64 is False.","commonSituations":"Reversed arithmetic in expressions like 0 - df['timestamp']; numpy broadcasting a scalar across a DatetimeIndex; mis-typed join keys.","solutions":["Reorder the expression so the DatetimeArray is on the left, or convert the left operand to a Timestamp.","Cast the numeric operand to a timedelta if a duration was intended: pd.Timedelta(...) - datetime_idx is still invalid — flip to datetime_idx - pd.Timedelta(...).","Convert the DatetimeArray to int64 ordinals before numeric subtraction: datetime_idx.astype('int64').","Validate the left operand's dtype is datetime-like before reflected subtraction."],"exampleFix":"// before\nout = 0 - datetime_idx  # TypeError: cannot subtract DatetimeArray from ndarray[int64]\n// after\nout = datetime_idx - datetime_idx[0]  # yields TimedeltaIndex","handlingStrategy":"validation","validationCode":"from pandas.api.types import is_datetime64_any_dtype\nif not (isinstance(other, (pd.Timestamp, pd.DatetimeIndex)) or is_datetime64_any_dtype(getattr(other, 'dtype', None))):\n    raise TypeError('left operand must be datelike for reflected subtraction from DatetimeArray')","typeGuard":"def valid_rsub_left(other) -> bool:\n    from pandas.api.types import is_datetime64_any_dtype\n    return isinstance(other, (pd.Timestamp, pd.DatetimeIndex)) or is_datetime64_any_dtype(getattr(other, 'dtype', None))","tryCatchPattern":"try:\n    out = other - datetime_idx\nexcept TypeError as e:\n    if 'cannot subtract' in str(e):\n        out = datetime_idx - other  # flip to direct op\n    else:\n        raise","preventionTips":["Avoid reflected subtraction (other - DatetimeArray) with non-datetike left operands.","Put the DatetimeArray on the left side of the expression.","Validate the left operand's dtype before reflected subtraction."],"tags":["subtraction","rsub","operand-order","datetime"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}