Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/pandas/core/tools/timedeltas.py : 19%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2timedelta support tools
3"""
5import numpy as np
7from pandas._libs.tslibs import NaT
8from pandas._libs.tslibs.timedeltas import Timedelta, parse_timedelta_unit
10from pandas.core.dtypes.common import is_list_like
11from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries
13from pandas.core.arrays.timedeltas import sequence_to_td64ns
16def to_timedelta(arg, unit="ns", errors="raise"):
17 """
18 Convert argument to timedelta.
20 Timedeltas are absolute differences in times, expressed in difference
21 units (e.g. days, hours, minutes, seconds). This method converts
22 an argument from a recognized timedelta format / value into
23 a Timedelta type.
25 Parameters
26 ----------
27 arg : str, timedelta, list-like or Series
28 The data to be converted to timedelta.
29 unit : str, default 'ns'
30 Denotes the unit of the arg. Possible values:
31 ('Y', 'M', 'W', 'D', 'days', 'day', 'hours', hour', 'hr',
32 'h', 'm', 'minute', 'min', 'minutes', 'T', 'S', 'seconds',
33 'sec', 'second', 'ms', 'milliseconds', 'millisecond',
34 'milli', 'millis', 'L', 'us', 'microseconds', 'microsecond',
35 'micro', 'micros', 'U', 'ns', 'nanoseconds', 'nano', 'nanos',
36 'nanosecond', 'N').
38 errors : {'ignore', 'raise', 'coerce'}, default 'raise'
39 - If 'raise', then invalid parsing will raise an exception.
40 - If 'coerce', then invalid parsing will be set as NaT.
41 - If 'ignore', then invalid parsing will return the input.
43 Returns
44 -------
45 timedelta64 or numpy.array of timedelta64
46 Output type returned if parsing succeeded.
48 See Also
49 --------
50 DataFrame.astype : Cast argument to a specified dtype.
51 to_datetime : Convert argument to datetime.
52 convert_dtypes : Convert dtypes.
54 Examples
55 --------
57 Parsing a single string to a Timedelta:
59 >>> pd.to_timedelta('1 days 06:05:01.00003')
60 Timedelta('1 days 06:05:01.000030')
61 >>> pd.to_timedelta('15.5us')
62 Timedelta('0 days 00:00:00.000015')
64 Parsing a list or array of strings:
66 >>> pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan'])
67 TimedeltaIndex(['1 days 06:05:01.000030', '0 days 00:00:00.000015', NaT],
68 dtype='timedelta64[ns]', freq=None)
70 Converting numbers by specifying the `unit` keyword argument:
72 >>> pd.to_timedelta(np.arange(5), unit='s')
73 TimedeltaIndex(['00:00:00', '00:00:01', '00:00:02',
74 '00:00:03', '00:00:04'],
75 dtype='timedelta64[ns]', freq=None)
76 >>> pd.to_timedelta(np.arange(5), unit='d')
77 TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],
78 dtype='timedelta64[ns]', freq=None)
79 """
80 unit = parse_timedelta_unit(unit)
82 if errors not in ("ignore", "raise", "coerce"):
83 raise ValueError("errors must be one of 'ignore', 'raise', or 'coerce'}")
85 if unit in {"Y", "y", "M"}:
86 raise ValueError(
87 "Units 'M' and 'Y' are no longer supported, as they do not "
88 "represent unambiguous timedelta values durations."
89 )
91 if arg is None:
92 return arg
93 elif isinstance(arg, ABCSeries):
94 values = _convert_listlike(arg._values, unit=unit, errors=errors)
95 return arg._constructor(values, index=arg.index, name=arg.name)
96 elif isinstance(arg, ABCIndexClass):
97 return _convert_listlike(arg, unit=unit, errors=errors, name=arg.name)
98 elif isinstance(arg, np.ndarray) and arg.ndim == 0:
99 # extract array scalar and process below
100 arg = arg.item()
101 elif is_list_like(arg) and getattr(arg, "ndim", 1) == 1:
102 return _convert_listlike(arg, unit=unit, errors=errors)
103 elif getattr(arg, "ndim", 1) > 1:
104 raise TypeError(
105 "arg must be a string, timedelta, list, tuple, 1-d array, or Series"
106 )
108 # ...so it must be a scalar value. Return scalar.
109 return _coerce_scalar_to_timedelta_type(arg, unit=unit, errors=errors)
112def _coerce_scalar_to_timedelta_type(r, unit="ns", errors="raise"):
113 """Convert string 'r' to a timedelta object."""
115 try:
116 result = Timedelta(r, unit)
117 except ValueError:
118 if errors == "raise":
119 raise
120 elif errors == "ignore":
121 return r
123 # coerce
124 result = NaT
126 return result
129def _convert_listlike(arg, unit="ns", errors="raise", name=None):
130 """Convert a list of objects to a timedelta index object."""
132 if isinstance(arg, (list, tuple)) or not hasattr(arg, "dtype"):
133 # This is needed only to ensure that in the case where we end up
134 # returning arg (errors == "ignore"), and where the input is a
135 # generator, we return a useful list-like instead of a
136 # used-up generator
137 arg = np.array(list(arg), dtype=object)
139 try:
140 value = sequence_to_td64ns(arg, unit=unit, errors=errors, copy=False)[0]
141 except ValueError:
142 if errors == "ignore":
143 return arg
144 else:
145 # This else-block accounts for the cases when errors='raise'
146 # and errors='coerce'. If errors == 'raise', these errors
147 # should be raised. If errors == 'coerce', we shouldn't
148 # expect any errors to be raised, since all parsing errors
149 # cause coercion to pd.NaT. However, if an error / bug is
150 # introduced that causes an Exception to be raised, we would
151 # like to surface it.
152 raise
154 from pandas import TimedeltaIndex
156 value = TimedeltaIndex(value, unit="ns", name=name)
157 return value