Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: raise exception on NaT in DatetimeIndex.astype('O') #1340 #1348

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion pandas/tseries/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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):
Expand Down
4 changes: 4 additions & 0 deletions pandas/tseries/tests/test_timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down