@@ -649,10 +649,12 @@ def astype_nansafe(arr, dtype, copy=True):
649649 if issubclass (dtype .type , text_type ):
650650 # in Py3 that's str, in Py2 that's unicode
651651 return lib .astype_unicode (arr .ravel ()).reshape (arr .shape )
652+
652653 elif issubclass (dtype .type , string_types ):
653654 return lib .astype_str (arr .ravel ()).reshape (arr .shape )
655+
654656 elif is_datetime64_dtype (arr ):
655- if dtype == object :
657+ if is_object_dtype ( dtype ) :
656658 return tslib .ints_to_pydatetime (arr .view (np .int64 ))
657659 elif dtype == np .int64 :
658660 return arr .view (dtype )
@@ -666,10 +668,10 @@ def astype_nansafe(arr, dtype, copy=True):
666668 to_dtype = dtype ))
667669
668670 elif is_timedelta64_dtype (arr ):
669- if dtype == np .int64 :
670- return arr .view (dtype )
671- elif dtype == object :
671+ if is_object_dtype (dtype ):
672672 return tslib .ints_to_pytimedelta (arr .view (np .int64 ))
673+ elif dtype == np .int64 :
674+ return arr .view (dtype )
673675
674676 # in py3, timedelta64[ns] are int64
675677 if ((PY3 and dtype not in [_INT64_DTYPE , _TD_DTYPE ]) or
@@ -696,9 +698,21 @@ def astype_nansafe(arr, dtype, copy=True):
696698 raise ValueError ('Cannot convert non-finite values (NA or inf) to '
697699 'integer' )
698700
699- elif is_object_dtype (arr .dtype ) and np .issubdtype (dtype .type , np .integer ):
701+ elif is_object_dtype (arr ):
702+
700703 # work around NumPy brokenness, #1987
701- return lib .astype_intsafe (arr .ravel (), dtype ).reshape (arr .shape )
704+ if np .issubdtype (dtype .type , np .integer ):
705+ return lib .astype_intsafe (arr .ravel (), dtype ).reshape (arr .shape )
706+
707+ # if we have a datetime/timedelta array of objects
708+ # then coerce to a proper dtype and recall astype_nansafe
709+
710+ elif is_datetime64_dtype (dtype ):
711+ from pandas import to_datetime
712+ return astype_nansafe (to_datetime (arr ).values , dtype , copy = copy )
713+ elif is_timedelta64_dtype (dtype ):
714+ from pandas import to_timedelta
715+ return astype_nansafe (to_timedelta (arr ).values , dtype , copy = copy )
702716
703717 if dtype .name in ("datetime64" , "timedelta64" ):
704718 msg = ("Passing in '{dtype}' dtype with no frequency is "
@@ -709,7 +723,6 @@ def astype_nansafe(arr, dtype, copy=True):
709723 dtype = np .dtype (dtype .name + "[ns]" )
710724
711725 if copy :
712-
713726 return arr .astype (dtype , copy = True )
714727 return arr .view (dtype )
715728
0 commit comments