Skip to content

Backport PR #52952: ERR: Raise a better error message with to_pydatetime and ArrowDtype(pa.date) #52989

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.0.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ Bug fixes

Other
~~~~~
-
- Raised a better error message when calling :func:`Series.dt.to_pydatetime` with :class:`ArrowDtype` with ``pyarrow.date32`` or ``pyarrow.date64`` type (:issue:`52812`)

.. ---------------------------------------------------------------------------
.. _whatsnew_202.contributors:
Expand Down
5 changes: 5 additions & 0 deletions pandas/core/arrays/arrow/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -2161,6 +2161,11 @@ def _dt_round(
return self._round_temporally("round", freq, ambiguous, nonexistent)

def _dt_to_pydatetime(self):
if pa.types.is_date(self.dtype.pyarrow_dtype):
raise ValueError(
f"to_pydatetime cannot be called with {self.dtype.pyarrow_dtype} type. "
"Convert to pyarrow timestamp type."
)
data = self._data.to_pylist()
if self._dtype.pyarrow_dtype.unit == "ns":
data = [None if ts is None else ts.to_pydatetime(warn=False) for ts in data]
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/extension/test_arrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2512,6 +2512,17 @@ def test_dt_to_pydatetime():
tm.assert_numpy_array_equal(result, expected)


@pytest.mark.parametrize("date_type", [32, 64])
def test_dt_to_pydatetime_date_error(date_type):
# GH 52812
ser = pd.Series(
[date(2022, 12, 31)],
dtype=ArrowDtype(getattr(pa, f"date{date_type}")()),
)
with pytest.raises(ValueError, match="to_pydatetime cannot be called with"):
ser.dt.to_pydatetime()


def test_dt_tz_localize_unsupported_tz_options():
ser = pd.Series(
[datetime(year=2023, month=1, day=2, hour=3), None],
Expand Down