3030 conversion ,
3131 iNaT ,
3232 ints_to_pydatetime ,
33- ints_to_pytimedelta ,
3433)
3534from pandas ._libs .tslibs .timezones import tz_compare
3635from pandas ._typing import AnyArrayLike , ArrayLike , Dtype , DtypeObj , Scalar
@@ -987,15 +986,21 @@ def astype_nansafe(
987986 elif not isinstance (dtype , np .dtype ):
988987 raise ValueError ("dtype must be np.dtype or ExtensionDtype" )
989988
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+
990997 if issubclass (dtype .type , str ):
991998 return lib .ensure_string_array (
992999 arr .ravel (), skipna = skipna , convert_na_value = False
9931000 ).reshape (arr .shape )
9941001
9951002 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 :
9991004 if isna (arr ).any ():
10001005 raise ValueError ("Cannot convert NaT values to integer" )
10011006 return arr .view (dtype )
@@ -1007,9 +1012,7 @@ def astype_nansafe(
10071012 raise TypeError (f"cannot astype a datetimelike from [{ arr .dtype } ] to [{ dtype } ]" )
10081013
10091014 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 :
10131016 if isna (arr ).any ():
10141017 raise ValueError ("Cannot convert NaT values to integer" )
10151018 return arr .view (dtype )
0 commit comments