Skip to content

modified changes for datetime and NaT Objects Behavior closes #43280 #43289

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

Closed
wants to merge 4 commits into from
Closed
Changes from 2 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
20 changes: 19 additions & 1 deletion pandas/core/tools/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,19 @@ def to_numeric(arg, errors="raise", downcast=None):
1 2.1
2 3.0
dtype: Float32

Datetime dTypes is supported

>>> s = pd.to_numeric(datetime(2021, 8, 22), errors="coerce")
0 20210822
dtype: Int64
>>> s = pd.to_numeric(pd.NaT, errors="coerce")
nan
>>> s = pd.to_numeric(pd.Series(datetime(2021, 8, 22)), errors="coerce")
0 20210822
dtype: Int64
>>> s = pd.to_numeric(pd.Series(pd.NaT), errors="coerce")
NaN
"""
if downcast not in (None, "integer", "signed", "unsigned", "float"):
raise ValueError("invalid downcasting method provided")
Expand Down Expand Up @@ -157,6 +170,11 @@ def to_numeric(arg, errors="raise", downcast=None):
return float(arg)
if is_number(arg):
return arg
if isinstance(arg , datetime):
if pd.isnull(arg):
return np.NaN
else:
return int(pd.to_datetime(arg).strftime("%Y%m%d"))
is_scalars = True
values = np.array([arg], dtype="O")
elif getattr(arg, "ndim", 1) > 1:
Expand All @@ -175,7 +193,7 @@ def to_numeric(arg, errors="raise", downcast=None):
if is_numeric_dtype(values_dtype):
pass
elif is_datetime_or_timedelta_dtype(values_dtype):
values = values.view(np.int64)

else:
values = ensure_object(values)
coerce_numeric = errors not in ("ignore", "raise")
Expand Down