diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 70d616ca72c1b..f32028fe7b2f5 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -629,4 +629,5 @@ Bug Fixes - Bug in ``pd.DataFrame`` when constructing an empty DataFrame with a string dtype (:issue:`9428`) - Bug in ``pd.unique`` for arrays with the ``datetime64`` or ``timedelta64`` dtype that meant an array with object dtype was returned instead the original dtype (:issue: `9431`) - Bug in ``DatetimeIndex.take`` and ``TimedeltaIndex.take`` may not raise ``IndexError`` against invalid index (:issue:`10295`) +- Bug in ``Series([np.nan]).astype('M8[ms]')``, which now returns ``Series([pd.NaT])`` (:issue:`10747`) - Bug in ``PeriodIndex.order`` reset freq (:issue:`10295`) diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index f14358452ec13..12a43986d32bd 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -3291,6 +3291,12 @@ def test_NaT_scalar(self): series[2] = val self.assertTrue(com.isnull(series[2])) + def test_NaT_cast(self): + # GH10747 + result = Series([np.nan]).astype('M8[ns]') + expected = Series([NaT]) + assert_series_equal(result, expected) + def test_set_none_nan(self): self.series[3] = None self.assertIs(self.series[3], NaT) diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index bf134a0a6d996..369993b4c54d1 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -3253,9 +3253,12 @@ def cast_to_nanoseconds(ndarray arr): unit = get_datetime64_unit(arr.flat[0]) for i in range(n): - pandas_datetime_to_datetimestruct(ivalues[i], unit, &dts) - iresult[i] = pandas_datetimestruct_to_datetime(PANDAS_FR_ns, &dts) - _check_dts_bounds(&dts) + if ivalues[i] != NPY_NAT: + pandas_datetime_to_datetimestruct(ivalues[i], unit, &dts) + iresult[i] = pandas_datetimestruct_to_datetime(PANDAS_FR_ns, &dts) + _check_dts_bounds(&dts) + else: + iresult[i] = NPY_NAT return result