17
17
import numpy .ma as ma
18
18
19
19
from pandas ._libs import lib
20
- from pandas ._libs .tslibs import (
21
- IncompatibleFrequency ,
22
- OutOfBoundsDatetime ,
23
- )
20
+ from pandas ._libs .tslibs import IncompatibleFrequency
24
21
from pandas ._typing import (
25
22
AnyArrayLike ,
26
23
ArrayLike ,
@@ -719,9 +716,7 @@ def _try_cast(
719
716
# while maybe_cast_to_datetime treats it as UTC
720
717
# see test_maybe_promote_any_numpy_dtype_with_datetimetz
721
718
722
- # error: Incompatible return value type (got "Union[ExtensionArray,
723
- # ndarray, List[Any]]", expected "Union[ExtensionArray, ndarray]")
724
- return maybe_cast_to_datetime (arr , dtype ) # type: ignore[return-value]
719
+ return maybe_cast_to_datetime (arr , dtype )
725
720
# TODO: copy?
726
721
727
722
array_type = dtype .construct_array_type ()._from_sequence
@@ -734,6 +729,9 @@ def _try_cast(
734
729
return subarr
735
730
return ensure_wrapped_if_datetimelike (arr ).astype (dtype , copy = copy )
736
731
732
+ elif dtype .kind in ["m" , "M" ]:
733
+ return maybe_cast_to_datetime (arr , dtype )
734
+
737
735
try :
738
736
# GH#15832: Check if we are requesting a numeric dtype and
739
737
# that we can convert the data to the requested dtype.
@@ -743,26 +741,16 @@ def _try_cast(
743
741
maybe_cast_to_integer_array (arr , dtype )
744
742
subarr = arr
745
743
else :
746
- subarr = maybe_cast_to_datetime (arr , dtype )
747
- if dtype is not None and dtype .kind == "M" :
748
- return subarr
744
+ subarr = arr
749
745
750
746
if not isinstance (subarr , ABCExtensionArray ):
751
747
# 4 tests fail if we move this to a try/except/else; see
752
748
# test_constructor_compound_dtypes, test_constructor_cast_failure
753
749
# test_constructor_dict_cast2, test_loc_setitem_dtype
754
750
subarr = construct_1d_ndarray_preserving_na (subarr , dtype , copy = copy )
755
751
756
- except OutOfBoundsDatetime :
757
- # in case of out of bound datetime64 -> always raise
758
- raise
759
- except (ValueError , TypeError ) as err :
760
- if dtype is not None and raise_cast_failure :
761
- raise
762
- elif "Cannot cast" in str (err ) or "cannot be converted to timedelta64" in str (
763
- err
764
- ):
765
- # via _disallow_mismatched_datetimelike
752
+ except (ValueError , TypeError ):
753
+ if raise_cast_failure :
766
754
raise
767
755
else :
768
756
subarr = np .array (arr , dtype = object , copy = copy )
0 commit comments