1212 is_timedelta64_dtype , _values_from_object ,
1313 is_list_like , isnull , _ensure_object )
1414
15- def to_timedelta (arg , unit = 'ns' , box = True ):
15+ def to_timedelta (arg , unit = 'ns' , box = True , coerce = False ):
1616 """
1717 Convert argument to timedelta
1818
@@ -23,6 +23,7 @@ def to_timedelta(arg, unit='ns', box=True):
2323 box : boolean, default True
2424 If True returns a Timedelta/TimedeltaIndex of the results
2525 if False returns a np.timedelta64 or ndarray of values of dtype timedelta64[ns]
26+ coerce : force errors to NaT (False by default)
2627
2728 Returns
2829 -------
@@ -43,14 +44,14 @@ def _convert_listlike(arg, box, unit):
4344 value = arg .astype ('timedelta64[{0}]' .format (unit )).astype ('timedelta64[ns]' )
4445 else :
4546 try :
46- value = tslib .array_to_timedelta64 (_ensure_object (arg ), unit = unit )
47+ value = tslib .array_to_timedelta64 (_ensure_object (arg ), unit = unit , coerce = coerce )
4748 except :
4849
4950 # try to process strings fast; may need to fallback
5051 try :
5152 value = np .array ([ _get_string_converter (r , unit = unit )() for r in arg ],dtype = 'm8[ns]' )
5253 except :
53- value = np .array ([ _coerce_scalar_to_timedelta_type (r , unit = unit ) for r in arg ])
54+ value = np .array ([ _coerce_scalar_to_timedelta_type (r , unit = unit , coerce = coerce ) for r in arg ])
5455
5556 if box :
5657 from pandas import TimedeltaIndex
@@ -67,7 +68,7 @@ def _convert_listlike(arg, box, unit):
6768 return _convert_listlike (arg , box = box , unit = unit )
6869
6970 # ...so it must be a scalar value. Return scalar.
70- return _coerce_scalar_to_timedelta_type (arg , unit = unit , box = box )
71+ return _coerce_scalar_to_timedelta_type (arg , unit = unit , box = box , coerce = coerce )
7172
7273_unit_map = {
7374 'Y' : 'Y' ,
@@ -135,7 +136,7 @@ def _validate_timedelta_unit(arg):
135136_full_search2 = re .compile ('' .join (
136137 ["^\s*(?P<neg>-?)\s*" ] + [ "(?P<" + p + ">\\ d+\.?\d*\s*(" + ss + "))?\\ s*" for p , ss in abbrevs ] + ['$' ]))
137138
138- def _coerce_scalar_to_timedelta_type (r , unit = 'ns' , box = True ):
139+ def _coerce_scalar_to_timedelta_type (r , unit = 'ns' , box = True , coerce = False ):
139140 """ convert strings to timedelta; coerce to Timedelta (if box), else np.timedelta64"""
140141
141142 if isinstance (r , compat .string_types ):
@@ -145,7 +146,7 @@ def _coerce_scalar_to_timedelta_type(r, unit='ns', box=True):
145146 r = converter ()
146147 unit = 'ns'
147148
148- result = tslib .convert_to_timedelta (r ,unit )
149+ result = tslib .convert_to_timedelta (r ,unit , coerce )
149150 if box :
150151 result = tslib .Timedelta (result )
151152
@@ -262,32 +263,3 @@ def convert(r=None, unit=None, m=m):
262263 # no converter
263264 raise ValueError ("cannot create timedelta string converter for [{0}]" .format (r ))
264265
265- def _possibly_cast_to_timedelta (value , coerce = True , dtype = None ):
266- """ try to cast to timedelta64, if already a timedeltalike, then make
267- sure that we are [ns] (as numpy 1.6.2 is very buggy in this regards,
268- don't force the conversion unless coerce is True
269-
270- if dtype is passed then this is the target dtype
271- """
272-
273- # deal with numpy not being able to handle certain timedelta operations
274- if isinstance (value , (ABCSeries , np .ndarray )):
275-
276- # i8 conversions
277- if value .dtype == 'int64' and np .dtype (dtype ) == 'timedelta64[ns]' :
278- value = value .astype ('timedelta64[ns]' )
279- return value
280- elif value .dtype .kind == 'm' :
281- if value .dtype != 'timedelta64[ns]' :
282- value = value .astype ('timedelta64[ns]' )
283- return value
284-
285- # we don't have a timedelta, but we want to try to convert to one (but
286- # don't force it)
287- if coerce :
288- new_value = tslib .array_to_timedelta64 (
289- _values_from_object (value ).astype (object ), coerce = False )
290- if new_value .dtype == 'i8' :
291- value = np .array (new_value , dtype = 'timedelta64[ns]' )
292-
293- return value
0 commit comments