{"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":1461,"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":1443,"sourceCodeEnd":1479,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/datetimelike.py#L1443-L1479","documentation":"Raised in __rsub__ when self.dtype.kind == 'M' (datetime) but the other operand has a dtype and is not datetimelike (other_is_dt64 is False). Pandas treats datetime - datetime as well-defined (-> timedelta), but `<other non-dt type> - datetime` is not, so the reflected subtraction is refused with a message naming both types and the other's dtype.","triggerScenarios":"np.array([1,2,3]) - DatetimeIndex(...); int Series - datetime Series; float64 array - DatetimeArray; object column minus a datetime column where inference did not classify it as datetimelike.","commonSituations":"Reflected arithmetic where the left operand is numeric/object and the right is a datetime column; subtraction order mistakes in elapsed-time calculations.","solutions":["Reverse the operand order so the datetime is on the left: datetime - datetime -> timedelta, or datetime - timedelta -> datetime.","If the left operand is numeric and represents offsets, convert it to timedelta first (pd.to_timedelta) before subtracting from a datetime.","Cast or infer the other operand so it is recognized as datetimelike if that was the intent."],"exampleFix":"// before\nres = nums - dta  # nums is int64 -> TypeError\n\n// after\nres = dta - nums.astype('timedelta64[s]')  # or dta - pd.to_timedelta(nums, unit='s')","handlingStrategy":"type-guard","validationCode":"import pandas as pd\n\ndef rsub_safe(dta, other):\n    other_dt = getattr(other, 'dtype', None)\n    if other_dt is not None and not pd.api.types.is_datetime64_any_dtype(other) and dta.dtype.kind == 'M':\n        raise TypeError(f'cannot subtract {type(dta).__name__} from non-datetime {other_dt}')\n    return other - dta","typeGuard":"import pandas as pd\n\ndef is_recognized_datetimelike(other) -> bool:\n    d = getattr(other, 'dtype', None)\n    if d is None:\n        return False\n    return d.kind in 'mM' or isinstance(d, pd.PeriodDtype)","tryCatchPattern":"try:\n    res = other - dta\nexcept TypeError as e:\n    if 'cannot subtract' in str(e) and 'from' in str(e):\n        res = dta - other  # reverse if a difference was intended\n    else:\n        raise","preventionTips":["Keep DatetimeArray on the left of subtraction: dta - other.","Convert numeric offsets to timedelta before combining with datetimes.","Avoid reflected subtraction with non-datetimelike left operands."],"tags":["datetime","arithmetic","rsub","type-error"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}