Skip to content

Commit

Permalink
Backport PR #51869 on branch 2.0.x (ENH: Add to_pydatetime for ArrowE…
Browse files Browse the repository at this point in the history
…xtensionArray) (#51870)

Backport PR #51869: ENH: Add to_pydatetime for ArrowExtensionArray

Co-authored-by: Matthew Roeschke <10647082+mroeschke@users.noreply.github.com>
  • Loading branch information
meeseeksmachine and mroeschke committed Mar 10, 2023
1 parent 9c9e9a5 commit 906e004
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
3 changes: 3 additions & 0 deletions pandas/core/arrays/arrow/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -1958,6 +1958,9 @@ def _dt_round(
):
return self._round_temporally("round", freq, ambiguous, nonexistent)

def _dt_to_pydatetime(self):
return np.array(self._data.to_pylist(), dtype=object)

def _dt_tz_localize(
self,
tz,
Expand Down
3 changes: 3 additions & 0 deletions pandas/core/indexes/accessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,9 @@ def _delegate_method(self, name: str, *args, **kwargs):

return result

def to_pydatetime(self):
return cast(ArrowExtensionArray, self._parent.array)._dt_to_pydatetime()

def isocalendar(self):
from pandas import DataFrame

Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/extension/test_arrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2261,6 +2261,19 @@ def test_dt_ceil_year_floor(freq, method):
tm.assert_series_equal(result, expected)


def test_dt_to_pydatetime():
# GH 51859
data = [datetime(2022, 1, 1), datetime(2023, 1, 1)]
ser = pd.Series(data, dtype=ArrowDtype(pa.timestamp("ns")))

result = ser.dt.to_pydatetime()
expected = np.array(data, dtype=object)
tm.assert_numpy_array_equal(result, expected)

expected = ser.astype("datetime64[ns]").dt.to_pydatetime()
tm.assert_numpy_array_equal(result, expected)


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

0 comments on commit 906e004

Please sign in to comment.