Skip to content

BUG: fix to_numeric raises TypeError for Timedelta and Timestamp scalar #59974

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
Oct 5, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 6 additions & 0 deletions pandas/core/tools/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@
lib,
missing as libmissing,
)
from pandas._libs.tslibs import (
Timedelta,
Timestamp,
)
from pandas.util._validators import check_dtype_backend

from pandas.core.dtypes.cast import maybe_downcast_numeric
Expand Down Expand Up @@ -189,6 +193,8 @@ def to_numeric(
return float(arg)
if is_number(arg):
return arg
if isinstance(arg, (Timedelta, Timestamp)):
return arg._value
is_scalars = True
values = np.array([arg], dtype="O")
elif getattr(arg, "ndim", 1) > 1:
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/tools/test_to_numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,21 @@ def test_timedelta(transform_assert_equal):
assert_equal(result, expected)


@pytest.mark.parametrize(
"scalar",
[
pd.Timedelta(1, "D"),
pd.Timestamp("2017-01-01T12"),
pd.Timestamp("2017-01-01T12", tz="US/Pacific"),
],
)
def test_timedelta_timestamp_scalar(scalar):
# GH#59944
result = to_numeric(scalar)
expected = to_numeric(Series(scalar))[0]
assert result == expected


def test_period(request, transform_assert_equal):
transform, assert_equal = transform_assert_equal

Expand Down