Skip to content

BUG: to_timedelta with ArrowDtype(pa.duration) #54298

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 2 commits into from
Aug 3, 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,7 @@ Timedelta
- :meth:`TimedeltaIndex.map` with ``na_action="ignore"`` now works as expected (:issue:`51644`)
- Bug in :class:`TimedeltaIndex` division or multiplication leading to ``.freq`` of "0 Days" instead of ``None`` (:issue:`51575`)
- Bug in :class:`Timedelta` with Numpy timedelta64 objects not properly raising ``ValueError`` (:issue:`52806`)
- Bug in :func:`to_timedelta` converting :class:`Series` or :class:`DataFrame` containing :class:`ArrowDtype` of ``pyarrow.duration`` to numpy ``timedelta64`` (:issue:`54298`)
- Bug in :meth:`Timedelta.__hash__`, raising an ``OutOfBoundsTimedelta`` on certain large values of second resolution (:issue:`54037`)
- Bug in :meth:`Timedelta.round` with values close to the implementation bounds returning incorrect results instead of raising ``OutOfBoundsTimedelta`` (:issue:`51494`)
- Bug in :meth:`arrays.TimedeltaArray.map` and :meth:`TimedeltaIndex.map`, where the supplied callable operated array-wise instead of element-wise (:issue:`51977`)
Expand Down
12 changes: 10 additions & 2 deletions pandas/core/tools/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from pandas.util._exceptions import find_stack_level

from pandas.core.dtypes.common import is_list_like
from pandas.core.dtypes.dtypes import ArrowDtype
from pandas.core.dtypes.generic import (
ABCIndex,
ABCSeries,
Expand All @@ -31,6 +32,7 @@
from pandas.core.arrays.timedeltas import sequence_to_td64ns

if TYPE_CHECKING:
from collections.abc import Hashable
from datetime import timedelta

from pandas._libs.tslibs.timedeltas import UnitChoices
Expand Down Expand Up @@ -242,17 +244,23 @@ def _coerce_scalar_to_timedelta_type(


def _convert_listlike(
arg, unit=None, errors: DateTimeErrorChoices = "raise", name=None
arg,
unit: UnitChoices | None = None,
errors: DateTimeErrorChoices = "raise",
name: Hashable | None = None,
Copy link
Member

Choose a reason for hiding this comment

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

i think Hashable includes None?

Copy link
Member Author

Choose a reason for hiding this comment

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

mypy doesn't complain when removing None, but looks like there's a ruff check that auto-annotates None here

):
"""Convert a list of objects to a timedelta index object."""
if isinstance(arg, (list, tuple)) or not hasattr(arg, "dtype"):
arg_dtype = getattr(arg, "dtype", None)
if isinstance(arg, (list, tuple)) or arg_dtype is None:
# This is needed only to ensure that in the case where we end up
# returning arg (errors == "ignore"), and where the input is a
# generator, we return a useful list-like instead of a
# used-up generator
if not hasattr(arg, "__array__"):
arg = list(arg)
arg = np.array(arg, dtype=object)
elif isinstance(arg_dtype, ArrowDtype) and arg_dtype.kind == "m":
return arg

try:
td64arr = sequence_to_td64ns(arg, unit=unit, errors=errors, copy=False)[0]
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/tools/test_to_timedelta.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,3 +306,12 @@ def test_from_numeric_arrow_dtype(any_numeric_ea_dtype):
result = to_timedelta(ser)
expected = Series([1, 2], dtype="timedelta64[ns]")
tm.assert_series_equal(result, expected)


@pytest.mark.parametrize("unit", ["ns", "ms"])
def test_from_timedelta_arrow_dtype(unit):
# GH 54298
pytest.importorskip("pyarrow")
expected = Series([timedelta(1)], dtype=f"duration[{unit}][pyarrow]")
result = to_timedelta(expected)
tm.assert_series_equal(result, expected)