Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/pandas/core/tools/timedeltas.py: 21%
68 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1"""
2timedelta support tools
3"""
4from __future__ import annotations
6from datetime import timedelta
7from typing import (
8 TYPE_CHECKING,
9 overload,
10)
12import numpy as np
14from pandas._libs import lib
15from pandas._libs.tslibs import (
16 NaT,
17 NaTType,
18)
19from pandas._libs.tslibs.timedeltas import (
20 Timedelta,
21 parse_timedelta_unit,
22)
24from pandas.core.dtypes.common import is_list_like
25from pandas.core.dtypes.generic import (
26 ABCIndex,
27 ABCSeries,
28)
30from pandas.core.arrays.timedeltas import sequence_to_td64ns
32if TYPE_CHECKING: 32 ↛ 33line 32 didn't jump to line 33, because the condition on line 32 was never true
33 from pandas._libs.tslibs.timedeltas import UnitChoices
34 from pandas._typing import (
35 ArrayLike,
36 DateTimeErrorChoices,
37 )
39 from pandas import (
40 Index,
41 Series,
42 TimedeltaIndex,
43 )
46@overload
47def to_timedelta(
48 arg: str | float | timedelta,
49 unit: UnitChoices | None = ...,
50 errors: DateTimeErrorChoices = ...,
51) -> Timedelta:
52 ...
55@overload
56def to_timedelta(
57 arg: Series,
58 unit: UnitChoices | None = ...,
59 errors: DateTimeErrorChoices = ...,
60) -> Series:
61 ...
64@overload
65def to_timedelta(
66 arg: list | tuple | range | ArrayLike | Index,
67 unit: UnitChoices | None = ...,
68 errors: DateTimeErrorChoices = ...,
69) -> TimedeltaIndex:
70 ...
73def to_timedelta(
74 arg: str
75 | int
76 | float
77 | timedelta
78 | list
79 | tuple
80 | range
81 | ArrayLike
82 | Index
83 | Series,
84 unit: UnitChoices | None = None,
85 errors: DateTimeErrorChoices = "raise",
86) -> Timedelta | TimedeltaIndex | Series:
87 """
88 Convert argument to timedelta.
90 Timedeltas are absolute differences in times, expressed in difference
91 units (e.g. days, hours, minutes, seconds). This method converts
92 an argument from a recognized timedelta format / value into
93 a Timedelta type.
95 Parameters
96 ----------
97 arg : str, timedelta, list-like or Series
98 The data to be converted to timedelta.
100 .. deprecated:: 1.2
101 Strings with units 'M', 'Y' and 'y' do not represent
102 unambiguous timedelta values and will be removed in a future version
104 unit : str, optional
105 Denotes the unit of the arg for numeric `arg`. Defaults to ``"ns"``.
107 Possible values:
109 * 'W'
110 * 'D' / 'days' / 'day'
111 * 'hours' / 'hour' / 'hr' / 'h'
112 * 'm' / 'minute' / 'min' / 'minutes' / 'T'
113 * 'S' / 'seconds' / 'sec' / 'second'
114 * 'ms' / 'milliseconds' / 'millisecond' / 'milli' / 'millis' / 'L'
115 * 'us' / 'microseconds' / 'microsecond' / 'micro' / 'micros' / 'U'
116 * 'ns' / 'nanoseconds' / 'nano' / 'nanos' / 'nanosecond' / 'N'
118 .. versionchanged:: 1.1.0
120 Must not be specified when `arg` context strings and
121 ``errors="raise"``.
123 errors : {'ignore', 'raise', 'coerce'}, default 'raise'
124 - If 'raise', then invalid parsing will raise an exception.
125 - If 'coerce', then invalid parsing will be set as NaT.
126 - If 'ignore', then invalid parsing will return the input.
128 Returns
129 -------
130 timedelta
131 If parsing succeeded.
132 Return type depends on input:
134 - list-like: TimedeltaIndex of timedelta64 dtype
135 - Series: Series of timedelta64 dtype
136 - scalar: Timedelta
138 See Also
139 --------
140 DataFrame.astype : Cast argument to a specified dtype.
141 to_datetime : Convert argument to datetime.
142 convert_dtypes : Convert dtypes.
144 Notes
145 -----
146 If the precision is higher than nanoseconds, the precision of the duration is
147 truncated to nanoseconds for string inputs.
149 Examples
150 --------
151 Parsing a single string to a Timedelta:
153 >>> pd.to_timedelta('1 days 06:05:01.00003')
154 Timedelta('1 days 06:05:01.000030')
155 >>> pd.to_timedelta('15.5us')
156 Timedelta('0 days 00:00:00.000015500')
158 Parsing a list or array of strings:
160 >>> pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan'])
161 TimedeltaIndex(['1 days 06:05:01.000030', '0 days 00:00:00.000015500', NaT],
162 dtype='timedelta64[ns]', freq=None)
164 Converting numbers by specifying the `unit` keyword argument:
166 >>> pd.to_timedelta(np.arange(5), unit='s')
167 TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:01', '0 days 00:00:02',
168 '0 days 00:00:03', '0 days 00:00:04'],
169 dtype='timedelta64[ns]', freq=None)
170 >>> pd.to_timedelta(np.arange(5), unit='d')
171 TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],
172 dtype='timedelta64[ns]', freq=None)
173 """
174 if unit is not None:
175 unit = parse_timedelta_unit(unit)
177 if errors not in ("ignore", "raise", "coerce"):
178 raise ValueError("errors must be one of 'ignore', 'raise', or 'coerce'.")
180 if unit in {"Y", "y", "M"}:
181 raise ValueError(
182 "Units 'M', 'Y', and 'y' are no longer supported, as they do not "
183 "represent unambiguous timedelta values durations."
184 )
186 if arg is None:
187 return arg
188 elif isinstance(arg, ABCSeries):
189 values = _convert_listlike(arg._values, unit=unit, errors=errors)
190 return arg._constructor(values, index=arg.index, name=arg.name)
191 elif isinstance(arg, ABCIndex):
192 return _convert_listlike(arg, unit=unit, errors=errors, name=arg.name)
193 elif isinstance(arg, np.ndarray) and arg.ndim == 0:
194 # extract array scalar and process below
195 # error: Incompatible types in assignment (expression has type "object",
196 # variable has type "Union[str, int, float, timedelta, List[Any],
197 # Tuple[Any, ...], Union[Union[ExtensionArray, ndarray[Any, Any]], Index,
198 # Series]]") [assignment]
199 arg = lib.item_from_zerodim(arg) # type: ignore[assignment]
200 elif is_list_like(arg) and getattr(arg, "ndim", 1) == 1:
201 return _convert_listlike(arg, unit=unit, errors=errors)
202 elif getattr(arg, "ndim", 1) > 1:
203 raise TypeError(
204 "arg must be a string, timedelta, list, tuple, 1-d array, or Series"
205 )
207 if isinstance(arg, str) and unit is not None:
208 raise ValueError("unit must not be specified if the input is/contains a str")
210 # ...so it must be a scalar value. Return scalar.
211 return _coerce_scalar_to_timedelta_type(arg, unit=unit, errors=errors)
214def _coerce_scalar_to_timedelta_type(r, unit="ns", errors="raise"):
215 """Convert string 'r' to a timedelta object."""
216 result: Timedelta | NaTType
218 try:
219 result = Timedelta(r, unit)
220 except ValueError:
221 if errors == "raise":
222 raise
223 elif errors == "ignore":
224 return r
226 # coerce
227 result = NaT
229 return result
232def _convert_listlike(arg, unit=None, errors="raise", name=None):
233 """Convert a list of objects to a timedelta index object."""
234 if isinstance(arg, (list, tuple)) or not hasattr(arg, "dtype"):
235 # This is needed only to ensure that in the case where we end up
236 # returning arg (errors == "ignore"), and where the input is a
237 # generator, we return a useful list-like instead of a
238 # used-up generator
239 arg = np.array(list(arg), dtype=object)
241 try:
242 td64arr = sequence_to_td64ns(arg, unit=unit, errors=errors, copy=False)[0]
243 except ValueError:
244 if errors == "ignore":
245 return arg
246 else:
247 # This else-block accounts for the cases when errors='raise'
248 # and errors='coerce'. If errors == 'raise', these errors
249 # should be raised. If errors == 'coerce', we shouldn't
250 # expect any errors to be raised, since all parsing errors
251 # cause coercion to pd.NaT. However, if an error / bug is
252 # introduced that causes an Exception to be raised, we would
253 # like to surface it.
254 raise
256 from pandas import TimedeltaIndex
258 value = TimedeltaIndex(td64arr, unit="ns", name=name)
259 return value