Skip to content

Commit d607694

Browse files
authored
ERR: Raise a better error message with to_pydatetime and ArrowDtype(pa.date) (#52952)
* ERR: Raise a better error message with to_pydatetime and ArrowDtype(pa.date) * Update pandas/tests/extension/test_arrow.py * Add warning * fix error message * Suggest to convert to pyarrow timestamp type first
1 parent d17eb8f commit d607694

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

Diff for: doc/source/whatsnew/v2.0.2.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ Bug fixes
3131

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

3636
.. ---------------------------------------------------------------------------
3737
.. _whatsnew_202.contributors:

Diff for: pandas/core/arrays/arrow/array.py

+5
Original file line numberDiff line numberDiff line change
@@ -2344,6 +2344,11 @@ def _dt_month_name(self, locale: str | None = None):
23442344
return type(self)(pc.strftime(self._pa_array, format="%B", locale=locale))
23452345

23462346
def _dt_to_pydatetime(self):
2347+
if pa.types.is_date(self.dtype.pyarrow_dtype):
2348+
raise ValueError(
2349+
f"to_pydatetime cannot be called with {self.dtype.pyarrow_dtype} type. "
2350+
"Convert to pyarrow timestamp type."
2351+
)
23472352
data = self._pa_array.to_pylist()
23482353
if self._dtype.pyarrow_dtype.unit == "ns":
23492354
data = [None if ts is None else ts.to_pydatetime(warn=False) for ts in data]

Diff for: pandas/tests/extension/test_arrow.py

+13
Original file line numberDiff line numberDiff line change
@@ -2615,6 +2615,19 @@ def test_dt_to_pydatetime():
26152615
tm.assert_numpy_array_equal(result, expected)
26162616

26172617

2618+
@pytest.mark.parametrize("date_type", [32, 64])
2619+
def test_dt_to_pydatetime_date_error(date_type):
2620+
# GH 52812
2621+
ser = pd.Series(
2622+
[date(2022, 12, 31)],
2623+
dtype=ArrowDtype(getattr(pa, f"date{date_type}")()),
2624+
)
2625+
msg = "The behavior of ArrowTemporalProperties.to_pydatetime is deprecated"
2626+
with tm.assert_produces_warning(FutureWarning, match=msg):
2627+
with pytest.raises(ValueError, match="to_pydatetime cannot be called with"):
2628+
ser.dt.to_pydatetime()
2629+
2630+
26182631
def test_dt_tz_localize_unsupported_tz_options():
26192632
ser = pd.Series(
26202633
[datetime(year=2023, month=1, day=2, hour=3), None],

0 commit comments

Comments
 (0)