Skip to content

BUG: to_datetime re-parsing Arrow-backed objects #53301

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 13 commits into from
Jul 11, 2023
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -321,11 +321,11 @@ Datetimelike
^^^^^^^^^^^^
- :meth:`DatetimeIndex.map` with ``na_action="ignore"`` now works as expected. (:issue:`51644`)
- Bug in :func:`date_range` when ``freq`` was a :class:`DateOffset` with ``nanoseconds`` (:issue:`46877`)
- Bug in :func:`to_datetime` converting :class:`Series` or :class:`DataFrame` containing :class:`arrays.ArrowExtensionArray` of ``pyarrow`` timestamps to numpy datetimes (:issue:`52545`)
- Bug in :meth:`Timestamp.round` with values close to the implementation bounds returning incorrect results instead of raising ``OutOfBoundsDatetime`` (:issue:`51494`)
- Bug in :meth:`arrays.DatetimeArray.map` and :meth:`DatetimeIndex.map`, where the supplied callable operated array-wise instead of element-wise (:issue:`51977`)
- Bug in constructing a :class:`Series` or :class:`DataFrame` from a datetime or timedelta scalar always inferring nanosecond resolution instead of inferring from the input (:issue:`52212`)
- Bug in parsing datetime strings with weekday but no day e.g. "2023 Sept Thu" incorrectly raising ``AttributeError`` instead of ``ValueError`` (:issue:`52659`)
-

Timedelta
^^^^^^^^^
Expand Down
11 changes: 10 additions & 1 deletion pandas/core/tools/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,10 @@
is_list_like,
is_numeric_dtype,
)
from pandas.core.dtypes.dtypes import DatetimeTZDtype
from pandas.core.dtypes.dtypes import (
ArrowDtype,
DatetimeTZDtype,
)
from pandas.core.dtypes.generic import (
ABCDataFrame,
ABCSeries,
Expand Down Expand Up @@ -400,6 +403,12 @@ def _convert_listlike_datetimes(
arg = arg.tz_convert(None).tz_localize("utc")
return arg

elif isinstance(arg_dtype, ArrowDtype) and arg_dtype.kind == "M":
# TODO: Combine with above if DTI/DTA supports Arrow timestamps
if utc:
arg = arg.astype("timestamp[ns, UTC][pyarrow]")
Copy link
Member

Choose a reason for hiding this comment

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

I'd rather use pd.ArrowDtype(pa...) here

Copy link
Member

Choose a reason for hiding this comment

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

.astype shouldn't allow converting a tz-naive to tzaware (or vice-versa). i think this should use tz_convert/tz_localize instead

Copy link
Member

Choose a reason for hiding this comment

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

(btw if .astype works on ArrowEA to convert tznaive to tzaware we probably want to change that to match the non-arrow raising behavior)

Copy link
Member Author

Choose a reason for hiding this comment

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

(btw if .astype works on ArrowEA to convert tznaive to tzaware we probably want to change that to match the non-arrow raising behavior)

Sure, I'll raise a PR after this one gets in.

return arg

elif lib.is_np_dtype(arg_dtype, "M"):
arg_dtype = cast(np.dtype, arg_dtype)
if not is_supported_unit(get_unit_from_dtype(arg_dtype)):
Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/tools/test_to_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -933,6 +933,23 @@ def test_to_datetime_dtarr(self, tz):
result = to_datetime(arr)
assert result is arr

@pytest.mark.parametrize("utc", [True, False])
@pytest.mark.parametrize("tz", [None, "US/Central"])
def test_to_datetime_arrow(self, tz, utc):
pa = pytest.importorskip("pyarrow")

dti = date_range("1965-04-03", periods=19, freq="2W", tz=tz)
dti_arrow = dti.astype(pd.ArrowDtype(pa.timestamp(unit="ns")))

result = to_datetime(dti_arrow, utc=utc)
expected = to_datetime(dti, utc=utc).astype(
f"timestamp[{'ns, UTC' if utc else 'ns'}][pyarrow]"
)
if not utc:
# Doesn't hold for utc=True, since that will astype
assert result is dti_arrow
tm.assert_index_equal(result, expected, exact=False)

def test_to_datetime_pydatetime(self):
actual = to_datetime(datetime(2008, 1, 15))
assert actual == datetime(2008, 1, 15)
Expand Down