diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index 4fe9130c3a0d1..e1b033eb88227 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -5,6 +5,7 @@ import numpy as np +from pandas.core.common import isnull from pandas.core.index import Index, Int64Index from pandas.tseries.frequencies import infer_freq, to_offset from pandas.tseries.offsets import DateOffset, generate_range, Tick @@ -532,6 +533,12 @@ def asobject(self): """ Convert to Index of datetime objects """ + if isnull(self).any(): + msg = 'DatetimeIndex with NaT cannot be converted to object' + raise ValueError(msg) + return self._get_object_index() + + def _get_object_index(self): boxed_values = _dt_box_array(self.asi8, self.offset, self.tz) return Index(boxed_values, dtype=object) @@ -1009,7 +1016,7 @@ def normalize(self): return DatetimeIndex(new_values, freq='infer', name=self.name) def __iter__(self): - return iter(self.asobject) + return iter(self._get_object_index()) def searchsorted(self, key, side='left'): if isinstance(key, np.ndarray): diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index 9a0d6e6490942..ec572e2268f13 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -910,6 +910,10 @@ def test_index_conversion(self): self.assertRaises(ValueError, DatetimeIndex, ['a', 'b', 'c', 'd']) + def test_object_convert_fail(self): + idx = DatetimeIndex([NaT]) + self.assertRaises(ValueError, idx.astype, 'O') + def test_setops_conversion_fail(self): index = self.frame.index