Skip to content

REF: re-use objects_to_datetime64ns in maybe_infer_to_datetimelike #40120

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
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
5 changes: 4 additions & 1 deletion pandas/core/arrays/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from typing import (
List,
Optional,
Tuple,
Union,
)

Expand Down Expand Up @@ -907,7 +908,9 @@ def f(x):
# Constructor Helpers


def sequence_to_td64ns(data, copy=False, unit=None, errors="raise"):
def sequence_to_td64ns(
data, copy=False, unit=None, errors="raise"
) -> Tuple[np.ndarray, Optional[Tick]]:
"""
Parameters
----------
Expand Down
56 changes: 34 additions & 22 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -1416,31 +1416,43 @@ def maybe_infer_to_datetimelike(value: Union[np.ndarray, List]):
return value

def try_datetime(v: np.ndarray) -> ArrayLike:
# safe coerce to datetime64
try:
# GH19671
# tznaive only
v = tslib.array_to_datetime(v, require_iso8601=True, errors="raise")[0]
except ValueError:
# Coerce to datetime64, datetime64tz, or in corner cases
# object[datetimes]
from pandas.core.arrays.datetimes import (
DatetimeArray,
objects_to_datetime64ns,
tz_to_dtype,
)

try:
# GH#19671 we pass require_iso8601 to be relatively strict
# when parsing strings.
vals, tz = objects_to_datetime64ns(
v,
require_iso8601=True,
dayfirst=False,
yearfirst=False,
allow_object=True,
)
except (ValueError, TypeError):
# e.g. <class 'numpy.timedelta64'> is not convertible to datetime
return v.reshape(shape)
else:
# we might have a sequence of the same-datetimes with tz's
# if so coerce to a DatetimeIndex; if they are not the same,
# then these stay as object dtype, xref GH19671
from pandas import DatetimeIndex

try:

values, tz = conversion.datetime_to_datetime64(v)
except (ValueError, TypeError):
pass
else:
dti = DatetimeIndex(values).tz_localize("UTC").tz_convert(tz=tz)
return dti._data
except TypeError:
# e.g. <class 'numpy.timedelta64'> is not convertible to datetime
pass

return v.reshape(shape)
# then these stay as object dtype, xref GH#19671

if vals.dtype == object:
# This is reachable bc allow_object=True, means we cast things
# to mixed-tz datetime objects (mostly). Only 1 test
# relies on this behavior, see GH#40111
return vals.reshape(shape)

dta = DatetimeArray._simple_new(vals.view("M8[ns]"), dtype=tz_to_dtype(tz))
if dta.tz is None:
# TODO(EA2D): conditional reshape kludge unnecessary with 2D EAs
return dta._ndarray.reshape(shape)
return dta

def try_timedelta(v: np.ndarray) -> np.ndarray:
# safe coerce to timedelta64
Expand Down