{"record":{"id":"c39d9da934d9a826","repo":"pandas-dev/pandas","slug":"cannot-subtract-type-self-name-from-type-o-c39d9d","errorCode":null,"errorMessage":"cannot subtract {type(self).__name__} from {type(other).__name__}","messagePattern":"cannot subtract (.+?) from (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/datetimelike.py","lineNumber":1466,"sourceCode":"            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\n\n    def __iadd__(self, other) -> Self:\n        result = self + other\n        self[:] = result[:]\n        return self\n\n    def __isub__(self, other) -> Self:\n        result = self - other\n        self[:] = result[:]\n        return self\n\n    # --------------------------------------------------------------\n    # Reductions\n","sourceCodeStart":1448,"sourceCodeEnd":1484,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/datetimelike.py#L1448-L1484","documentation":"Raised by __rsub__ as a final guard when the flipped subtraction (self - other) produces a datetime-kind result, meaning the reflected op other - self would have yielded a datetime — which is not a meaningful 'subtraction from other'. Improved message introduced in GH#59571.","triggerScenarios":"Subtracting a TimedeltaArray from a non-datelike operand in reflected form, where the internal flip lands back in datetime dtype; reached at line 1466 after the flip computation at line 1463.","commonSituations":"Generic reflected arithmetic in numpy/pandas expressions; building expressions like list_like - timedelta_idx where list_like is object dtype containing datetimes.","solutions":["Reorder the expression so the operation is direct, not reflected.","Convert object-dtype operands to explicit DatetimeArray/Timestamp before subtracting.","Use pd.to_datetime(other) - timedelta_idx to make the intent explicit.","Inspect intermediate dtypes to ensure the result is timedelta, not datetime."],"exampleFix":"// before\nout = object_series - timedelta_idx  # TypeError: cannot subtract TimedeltaArray from Series\n// after\nout = pd.to_datetime(object_series) - timedelta_idx","handlingStrategy":"validation","validationCode":"if getattr(other, 'dtype', None) == object:\n    other = pd.to_datetime(other)\nout = other - timedelta_idx","typeGuard":"def needs_datetime_conversion(other) -> bool:\n    return getattr(other, 'dtype', None) == object","tryCatchPattern":"try:\n    out = other - timedelta_idx\nexcept TypeError as e:\n    if 'cannot subtract' in str(e) and 'from' in str(e):\n        out = pd.to_datetime(other) - timedelta_idx\n    else:\n        raise","preventionTips":["Convert object-dtype operands to DatetimeArray before reflected subtraction from TimedeltaArray.","Prefer direct (non-reflected) subtraction expressions.","Inspect intermediate dtypes to ensure a timedelta result."],"tags":["subtraction","rsub","operand-order","timedelta"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}