Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: Raise TypeError when subracting DateTimeArray and other date types #59901

Closed
7 changes: 6 additions & 1 deletion pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import warnings

import numpy as np
import pandas
Copy link
Member

@rhshadrach rhshadrach Sep 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We shouldn't be importing pandas at the top of a module like this - it will cause import cycles. Search for where DatetimeArray is imported in other parts of the code and follow those examples.

Copy link
Member

@rhshadrach rhshadrach Sep 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In general, search what you want to import and see how other code does it.

grep --include \*.py -nre ".*import.*DatetimeArray"
pandas/core/ops/array_ops.py:535:            from pandas.core.arrays import DatetimeArray
pandas/core/dtypes/dtypes.py:858:        from pandas.core.arrays import DatetimeArray
pandas/core/dtypes/dtypes.py:944:        from pandas.core.arrays import DatetimeArray
pandas/core/dtypes/astype.py:105:            from pandas.core.arrays import DatetimeArray

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @rhshadrach, I have removed this


from pandas._config import using_string_dtype
from pandas._config.config import get_option
Expand Down Expand Up @@ -1488,7 +1489,11 @@ def __rsub__(self, other):
return (-self) + other

# We get here with e.g. datetime objects
return -(self - other)
datetime_result = self - other
if isinstance(datetime_result, pandas.core.arrays.datetimes.DatetimeArray):
raise TypeError("TypeError: unsupported operand type(s) for -: "
f"'{type(self).__name__}' and '{type(other).__name__}'")
return -(datetime_result)

def __iadd__(self, other) -> Self:
result = self + other
Expand Down
Loading