30
30
conversion ,
31
31
iNaT ,
32
32
ints_to_pydatetime ,
33
- ints_to_pytimedelta ,
34
33
)
35
34
from pandas ._libs .tslibs .timezones import tz_compare
36
35
from pandas ._typing import AnyArrayLike , ArrayLike , Dtype , DtypeObj , Scalar
@@ -987,15 +986,21 @@ def astype_nansafe(
987
986
elif not isinstance (dtype , np .dtype ):
988
987
raise ValueError ("dtype must be np.dtype or ExtensionDtype" )
989
988
989
+ if arr .dtype .kind in ["m" , "M" ] and (
990
+ issubclass (dtype .type , str ) or dtype == object
991
+ ):
992
+ from pandas .core .construction import ensure_wrapped_if_datetimelike
993
+
994
+ arr = ensure_wrapped_if_datetimelike (arr )
995
+ return arr .astype (dtype , copy = copy )
996
+
990
997
if issubclass (dtype .type , str ):
991
998
return lib .ensure_string_array (
992
999
arr .ravel (), skipna = skipna , convert_na_value = False
993
1000
).reshape (arr .shape )
994
1001
995
1002
elif is_datetime64_dtype (arr ):
996
- if is_object_dtype (dtype ):
997
- return ints_to_pydatetime (arr .view (np .int64 ))
998
- elif dtype == np .int64 :
1003
+ if dtype == np .int64 :
999
1004
if isna (arr ).any ():
1000
1005
raise ValueError ("Cannot convert NaT values to integer" )
1001
1006
return arr .view (dtype )
@@ -1007,9 +1012,7 @@ def astype_nansafe(
1007
1012
raise TypeError (f"cannot astype a datetimelike from [{ arr .dtype } ] to [{ dtype } ]" )
1008
1013
1009
1014
elif is_timedelta64_dtype (arr ):
1010
- if is_object_dtype (dtype ):
1011
- return ints_to_pytimedelta (arr .view (np .int64 ))
1012
- elif dtype == np .int64 :
1015
+ if dtype == np .int64 :
1013
1016
if isna (arr ).any ():
1014
1017
raise ValueError ("Cannot convert NaT values to integer" )
1015
1018
return arr .view (dtype )
0 commit comments