24
24
OutOfBoundsDatetime ,
25
25
Timedelta ,
26
26
Timestamp ,
27
- conversion ,
28
27
iNaT ,
29
28
nat_strings ,
30
29
parsing ,
41
40
ArrayLike ,
42
41
DateTimeErrorChoices ,
43
42
Timezone ,
43
+ npt ,
44
44
)
45
45
from pandas .util ._exceptions import find_stack_level
46
46
@@ -467,8 +467,6 @@ def _array_strptime_with_fallback(
467
467
468
468
try :
469
469
result , timezones = array_strptime (arg , fmt , exact = exact , errors = errors )
470
- if "%Z" in fmt or "%z" in fmt :
471
- return _return_parsed_timezone_results (result , timezones , tz , name )
472
470
except OutOfBoundsDatetime :
473
471
if errors == "raise" :
474
472
raise
@@ -494,6 +492,9 @@ def _array_strptime_with_fallback(
494
492
else :
495
493
# Indicates to the caller to fallback to objects_to_datetime64ns
496
494
return None
495
+ else :
496
+ if "%Z" in fmt or "%z" in fmt :
497
+ return _return_parsed_timezone_results (result , timezones , tz , name )
497
498
498
499
return _box_as_indexlike (result , utc = utc , name = name )
499
500
@@ -512,38 +513,28 @@ def _to_datetime_with_format(
512
513
Try parsing with the given format, returning None on failure.
513
514
"""
514
515
result = None
515
- try :
516
- # shortcut formatting here
517
- if fmt == "%Y%m%d" :
518
- # pass orig_arg as float-dtype may have been converted to
519
- # datetime64[ns]
520
- orig_arg = ensure_object (orig_arg )
521
- try :
522
- # may return None without raising
523
- result = _attempt_YYYYMMDD (orig_arg , errors = errors )
524
- except (ValueError , TypeError , OutOfBoundsDatetime ) as err :
525
- raise ValueError (
526
- "cannot convert the input to '%Y%m%d' date format"
527
- ) from err
528
- if result is not None :
529
- utc = tz == "utc"
530
- return _box_as_indexlike (result , utc = utc , name = name )
531
516
532
- # fallback
533
- res = _array_strptime_with_fallback (
534
- arg , name , tz , fmt , exact , errors , infer_datetime_format
535
- )
536
- return res
537
-
538
- except ValueError as err :
539
- # Fallback to try to convert datetime objects if timezone-aware
540
- # datetime objects are found without passing `utc=True`
517
+ # shortcut formatting here
518
+ if fmt == "%Y%m%d" :
519
+ # pass orig_arg as float-dtype may have been converted to
520
+ # datetime64[ns]
521
+ orig_arg = ensure_object (orig_arg )
541
522
try :
542
- values , tz = conversion .datetime_to_datetime64 (arg )
543
- dta = DatetimeArray (values , dtype = tz_to_dtype (tz ))
544
- return DatetimeIndex ._simple_new (dta , name = name )
545
- except (ValueError , TypeError ):
546
- raise err
523
+ # may return None without raising
524
+ result = _attempt_YYYYMMDD (orig_arg , errors = errors )
525
+ except (ValueError , TypeError , OutOfBoundsDatetime ) as err :
526
+ raise ValueError (
527
+ "cannot convert the input to '%Y%m%d' date format"
528
+ ) from err
529
+ if result is not None :
530
+ utc = tz == "utc"
531
+ return _box_as_indexlike (result , utc = utc , name = name )
532
+
533
+ # fallback
534
+ res = _array_strptime_with_fallback (
535
+ arg , name , tz , fmt , exact , errors , infer_datetime_format
536
+ )
537
+ return res
547
538
548
539
549
540
def _to_datetime_with_unit (arg , unit , name , tz , errors : str ) -> Index :
@@ -1007,17 +998,6 @@ def to_datetime(
1007
998
DatetimeIndex(['2020-01-01 01:00:00-01:00', '2020-01-01 02:00:00-01:00'],
1008
999
dtype='datetime64[ns, pytz.FixedOffset(-60)]', freq=None)
1009
1000
1010
- - Finally, mixing timezone-aware strings and :class:`datetime.datetime` always
1011
- raises an error, even if the elements all have the same time offset.
1012
-
1013
- >>> from datetime import datetime, timezone, timedelta
1014
- >>> d = datetime(2020, 1, 1, 18, tzinfo=timezone(-timedelta(hours=1)))
1015
- >>> pd.to_datetime(["2020-01-01 17:00 -0100", d])
1016
- Traceback (most recent call last):
1017
- ...
1018
- ValueError: Tz-aware datetime.datetime cannot be converted to datetime64
1019
- unless utc=True
1020
-
1021
1001
|
1022
1002
1023
1003
Setting ``utc=True`` solves most of the above issues:
@@ -1243,7 +1223,7 @@ def coerce(values):
1243
1223
return values
1244
1224
1245
1225
1246
- def _attempt_YYYYMMDD (arg : np .ndarray , errors : str ) -> np .ndarray | None :
1226
+ def _attempt_YYYYMMDD (arg : npt . NDArray [ np .object_ ] , errors : str ) -> np .ndarray | None :
1247
1227
"""
1248
1228
try to parse the YYYYMMDD/%Y%m%d format, try to deal with NaT-like,
1249
1229
arg is a passed in as an object dtype, but could really be ints/strings
@@ -1257,7 +1237,7 @@ def _attempt_YYYYMMDD(arg: np.ndarray, errors: str) -> np.ndarray | None:
1257
1237
1258
1238
def calc (carg ):
1259
1239
# calculate the actual result
1260
- carg = carg .astype (object )
1240
+ carg = carg .astype (object , copy = False )
1261
1241
parsed = parsing .try_parse_year_month_day (
1262
1242
carg / 10000 , carg / 100 % 100 , carg % 100
1263
1243
)
0 commit comments