Skip to content

ENH: Add to_pydatetime for ArrowExtensionArray #51869

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 1 commit into from
Mar 9, 2023
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
3 changes: 3 additions & 0 deletions pandas/core/arrays/arrow/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -2090,6 +2090,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 @@ -2248,6 +2248,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