@@ -1416,31 +1416,43 @@ def maybe_infer_to_datetimelike(value: Union[np.ndarray, List]):
1416
1416
return value
1417
1417
1418
1418
def try_datetime (v : np .ndarray ) -> ArrayLike :
1419
- # safe coerce to datetime64
1420
- try :
1421
- # GH19671
1422
- # tznaive only
1423
- v = tslib .array_to_datetime (v , require_iso8601 = True , errors = "raise" )[0 ]
1424
- except ValueError :
1419
+ # Coerce to datetime64, datetime64tz, or in corner cases
1420
+ # object[datetimes]
1421
+ from pandas .core .arrays .datetimes import (
1422
+ DatetimeArray ,
1423
+ objects_to_datetime64ns ,
1424
+ tz_to_dtype ,
1425
+ )
1425
1426
1427
+ try :
1428
+ # GH#19671 we pass require_iso8601 to be relatively strict
1429
+ # when parsing strings.
1430
+ vals , tz = objects_to_datetime64ns (
1431
+ v ,
1432
+ require_iso8601 = True ,
1433
+ dayfirst = False ,
1434
+ yearfirst = False ,
1435
+ allow_object = True ,
1436
+ )
1437
+ except (ValueError , TypeError ):
1438
+ # e.g. <class 'numpy.timedelta64'> is not convertible to datetime
1439
+ return v .reshape (shape )
1440
+ else :
1426
1441
# we might have a sequence of the same-datetimes with tz's
1427
1442
# if so coerce to a DatetimeIndex; if they are not the same,
1428
- # then these stay as object dtype, xref GH19671
1429
- from pandas import DatetimeIndex
1430
-
1431
- try :
1432
-
1433
- values , tz = conversion .datetime_to_datetime64 (v )
1434
- except (ValueError , TypeError ):
1435
- pass
1436
- else :
1437
- dti = DatetimeIndex (values ).tz_localize ("UTC" ).tz_convert (tz = tz )
1438
- return dti ._data
1439
- except TypeError :
1440
- # e.g. <class 'numpy.timedelta64'> is not convertible to datetime
1441
- pass
1442
-
1443
- return v .reshape (shape )
1443
+ # then these stay as object dtype, xref GH#19671
1444
+
1445
+ if vals .dtype == object :
1446
+ # This is reachable bc allow_object=True, means we cast things
1447
+ # to mixed-tz datetime objects (mostly). Only 1 test
1448
+ # relies on this behavior, see GH#40111
1449
+ return vals .reshape (shape )
1450
+
1451
+ dta = DatetimeArray ._simple_new (vals .view ("M8[ns]" ), dtype = tz_to_dtype (tz ))
1452
+ if dta .tz is None :
1453
+ # TODO(EA2D): conditional reshape kludge unnecessary with 2D EAs
1454
+ return dta ._ndarray .reshape (shape )
1455
+ return dta
1444
1456
1445
1457
def try_timedelta (v : np .ndarray ) -> np .ndarray :
1446
1458
# safe coerce to timedelta64
0 commit comments