Skip to content

Commit dac4d0e

Browse files
Chang Shewesm
Chang She
authored andcommitted
BUG: raise exception on NaT in DatetimeIndex.astype('O') #1340
1 parent d3dd8db commit dac4d0e

File tree

2 files changed

+8
-0
lines changed

2 files changed

+8
-0
lines changed

pandas/tseries/index.py

+4
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
import numpy as np
77

8+
from pandas.core.common import isnull
89
from pandas.core.index import Index, Int64Index
910
from pandas.tseries.frequencies import infer_freq, to_offset
1011
from pandas.tseries.offsets import DateOffset, generate_range, Tick
@@ -513,6 +514,9 @@ def astype(self, dtype):
513514
dtype = np.dtype(dtype)
514515

515516
if dtype == np.object_:
517+
if isnull(self).any():
518+
msg = 'DatetimeIndex with NaT cannot be converted to object'
519+
raise ValueError(msg)
516520
return self.asobject
517521
return Index.astype(self, dtype)
518522

pandas/tseries/tests/test_timeseries.py

+4
Original file line numberDiff line numberDiff line change
@@ -945,6 +945,10 @@ def test_index_conversion(self):
945945

946946
self.assertRaises(ValueError, DatetimeIndex, ['a', 'b', 'c', 'd'])
947947

948+
def test_object_convert_fail(self):
949+
idx = DatetimeIndex([NaT])
950+
self.assertRaises(ValueError, idx.astype, 'O')
951+
948952
def test_setops_conversion_fail(self):
949953
index = self.frame.index
950954

0 commit comments

Comments
 (0)