{"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":1475,"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":1457,"sourceCodeEnd":1493,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/datetimelike.py#L1457-L1493","documentation":"Raised in __rsub__ (GH#59571) as a clearer follow-up message when the flipped subtraction `self - other` produced a result whose dtype kind is 'M' (datetime). This shape indicates `<something> - datetime` would have yielded datetimes, which is nonsensical — the original operation is rejected with both type names so the user can see the operand confusion.","triggerScenarios":"Subtracting a DatetimeArray from an object-dtype collection of datetimes that did not get inferred as datetimelike; e.g. list_of_datetimes - DatetimeIndex where the left stays object dtype and the flip yields datetime64.","commonSituations":"Reflected arithmetic with Python datetime objects held in an object array; user code that subtracts dates from non-date containers and gets a misleading datetime result.","solutions":["Convert the left operand to a DatetimeArray via pd.to_datetime so the standard datetime - datetime path (-> timedelta) is taken.","Reorder the operation so a DatetimeArray is on the left: dta - other.","Inspect dtype(other): if it is object containing datetimes, call pd.to_datetime(other) first."],"exampleFix":"// before\nres = obj_dates - dta  # object array of datetimes - DatetimeArray -> TypeError\n\n// after\nimport pandas as pd\nres = pd.to_datetime(obj_dates) - dta  # DatetimeArray - DatetimeArray -> TimedeltaIndex","handlingStrategy":"validation","validationCode":"import pandas as pd\n\ndef rsub_object_safe(other, dta):\n    if hasattr(other, 'dtype') and other.dtype == object:\n        other = pd.to_datetime(other)\n    return other - dta","typeGuard":"import pandas as pd\n\ndef is_object_array_of_datetimes(a) -> bool:\n    if getattr(a, 'dtype', None) != object:\n        return False\n    return pd.api.types.infer_dtype(a, skipna=True) in ('datetime', 'datetime64')","tryCatchPattern":"try:\n    res = other - dta\nexcept TypeError as e:\n    if 'cannot subtract' in str(e):\n        res = pd.to_datetime(other) - dta\n    else:\n        raise","preventionTips":["Convert object-dtype datetime containers via pd.to_datetime before subtraction.","Keep DatetimeArray on the left when computing differences.","Run pd.api.types.infer_dtype on object columns before arithmetic."],"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"}