def test_array_of_dt64_nat_raises(self): # GH#39462 nat = np.datetime64("NaT", "ns") arr = np.array([nat], dtype=object) # TODO: should be TypeError? msg = "Invalid type for timedelta scalar" with pytest.raises(ValueError, match=msg): TimedeltaIndex(arr) with pytest.raises(ValueError, match=msg): TimedeltaArray._from_sequence(arr) with pytest.raises(ValueError, match=msg): sequence_to_td64ns(arr)
def _convert_listlike(arg, unit=None, errors="raise", name=None): """Convert a list of objects to a timedelta index object.""" if isinstance(arg, (list, tuple)) or not hasattr(arg, "dtype"): # This is needed only to ensure that in the case where we end up # returning arg (errors == "ignore"), and where the input is a # generator, we return a useful list-like instead of a # used-up generator arg = np.array(list(arg), dtype=object) try: value = sequence_to_td64ns(arg, unit=unit, errors=errors, copy=False)[0] except ValueError: if errors == "ignore": return arg else: # This else-block accounts for the cases when errors='raise' # and errors='coerce'. If errors == 'raise', these errors # should be raised. If errors == 'coerce', we shouldn't # expect any errors to be raised, since all parsing errors # cause coercion to pd.NaT. However, if an error / bug is # introduced that causes an Exception to be raised, we would # like to surface it. raise from pandas import TimedeltaIndex # error: Incompatible types in assignment (expression has type "TimedeltaIndex", # variable has type "ndarray") value = TimedeltaIndex(value, unit="ns", name=name) # type: ignore[assignment] return value
def _convert_listlike(arg, unit='ns', box=True, errors='raise', name=None): """Convert a list of objects to a timedelta index object.""" if isinstance(arg, (list, tuple)) or not hasattr(arg, 'dtype'): # This is needed only to ensure that in the case where we end up # returning arg (errors == "ignore"), and where the input is a # generator, we return a useful list-like instead of a # used-up generator arg = np.array(list(arg), dtype=object) try: value = sequence_to_td64ns(arg, unit=unit, errors=errors, copy=False)[0] except ValueError: if errors == 'ignore': return arg else: # This else-block accounts for the cases when errors='raise' # and errors='coerce'. If errors == 'raise', these errors # should be raised. If errors == 'coerce', we shouldn't # expect any errors to be raised, since all parsing errors # cause coercion to pd.NaT. However, if an error / bug is # introduced that causes an Exception to be raised, we would # like to surface it. raise if box: from pandas import TimedeltaIndex value = TimedeltaIndex(value, unit='ns', name=name) return value
def __new__(cls, data=None, unit=None, freq=None, start=None, end=None, periods=None, closed=None, dtype=None, copy=False, name=None, verify_integrity=True): freq, freq_infer = dtl.maybe_infer_freq(freq) if data is None: # TODO: Remove this block and associated kwargs; GH#20535 result = cls._generate_range(start, end, periods, freq, closed=closed) result.name = name return result if is_scalar(data): raise TypeError('{cls}() must be called with a ' 'collection of some kind, {data} was passed' .format(cls=cls.__name__, data=repr(data))) if isinstance(data, TimedeltaIndex) and freq is None and name is None: if copy: return data.copy() else: return data._shallow_copy() # - Cases checked above all return/raise before reaching here - # data, inferred_freq = sequence_to_td64ns(data, copy=copy, unit=unit) if inferred_freq is not None: if freq is not None and freq != inferred_freq: raise ValueError('Inferred frequency {inferred} from passed ' 'values does not conform to passed frequency ' '{passed}' .format(inferred=inferred_freq, passed=freq.freqstr)) elif freq_infer: freq = inferred_freq freq_infer = False verify_integrity = False subarr = cls._simple_new(data, name=name, freq=freq) # check that we are matching freqs if verify_integrity and len(subarr) > 0: if freq is not None and not freq_infer: cls._validate_frequency(subarr, freq) if freq_infer: subarr.freq = to_offset(subarr.inferred_freq) return subarr
def __new__(cls, data=None, unit=None, freq=None, start=None, end=None, periods=None, closed=None, dtype=None, copy=False, name=None, verify_integrity=None): if verify_integrity is not None: warnings.warn( "The 'verify_integrity' argument is deprecated, " "will be removed in a future version.", FutureWarning, stacklevel=2) else: verify_integrity = True freq, freq_infer = dtl.maybe_infer_freq(freq) if data is None: warnings.warn( "Creating a TimedeltaIndex by passing range " "endpoints is deprecated. Use " "`pandas.timedelta_range` instead.", FutureWarning, stacklevel=2) result = cls._generate_range(start, end, periods, freq, closed=closed) result.name = name return result if is_scalar(data): raise TypeError( '{cls}() must be called with a ' 'collection of some kind, {data} was passed'.format( cls=cls.__name__, data=repr(data))) if isinstance(data, TimedeltaIndex) and freq is None and name is None: if copy: return data.copy() else: return data._shallow_copy() # - Cases checked above all return/raise before reaching here - # data, inferred_freq = sequence_to_td64ns(data, copy=copy, unit=unit) if inferred_freq is not None: if freq is not None and freq != inferred_freq: raise ValueError('Inferred frequency {inferred} from passed ' 'values does not conform to passed frequency ' '{passed}'.format(inferred=inferred_freq, passed=freq.freqstr)) elif freq_infer: freq = inferred_freq freq_infer = False verify_integrity = False subarr = cls._simple_new(data, name=name, freq=freq) # check that we are matching freqs if verify_integrity and len(subarr) > 0: if freq is not None and not freq_infer: cls._validate_frequency(subarr, freq) if freq_infer: subarr.freq = to_offset(subarr.inferred_freq) return subarr