2
timedelta support tools
7
from pandas._libs.tslibs import NaT
8
from pandas._libs.tslibs.timedeltas import Timedelta, parse_timedelta_unit
10
from pandas.core.dtypes.common import is_list_like
11
from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries
13
from pandas.core.arrays.timedeltas import sequence_to_td64ns
16
def to_timedelta(arg, unit=None, errors="raise"):
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
27
arg : str, timedelta, list-like or Series
28
The data to be converted to timedelta.
30
Denotes the unit of the arg for numeric `arg`. Defaults to ``"ns"``.
35
* 'D' / 'days' / 'day'
36
* 'hours' / 'hour' / 'hr' / 'h'
37
* 'm' / 'minute' / 'min' / 'minutes' / 'T'
38
* 'S' / 'seconds' / 'sec' / 'second'
39
* 'ms' / 'milliseconds' / 'millisecond' / 'milli' / 'millis' / 'L'
40
* 'us' / 'microseconds' / 'microsecond' / 'micro' / 'micros' / 'U'
41
* 'ns' / 'nanoseconds' / 'nano' / 'nanos' / 'nanosecond' / 'N'
43
.. versionchanged:: 1.1.0
45
Must not be specified when `arg` context strings and
48
errors : {'ignore', 'raise', 'coerce'}, default 'raise'
49
- If 'raise', then invalid parsing will raise an exception.
50
- If 'coerce', then invalid parsing will be set as NaT.
51
- If 'ignore', then invalid parsing will return the input.
55
timedelta64 or numpy.array of timedelta64
56
Output type returned if parsing succeeded.
60
DataFrame.astype : Cast argument to a specified dtype.
61
to_datetime : Convert argument to datetime.
62
convert_dtypes : Convert dtypes.
66
Parsing a single string to a Timedelta:
68
>>> pd.to_timedelta('1 days 06:05:01.00003')
69
Timedelta('1 days 06:05:01.000030')
70
>>> pd.to_timedelta('15.5us')
71
Timedelta('0 days 00:00:00.000015500')
73
Parsing a list or array of strings:
75
>>> pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan'])
76
TimedeltaIndex(['1 days 06:05:01.000030', '0 days 00:00:00.000015500', NaT],
77
dtype='timedelta64[ns]', freq=None)
79
Converting numbers by specifying the `unit` keyword argument:
81
>>> pd.to_timedelta(np.arange(5), unit='s')
82
TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:01', '0 days 00:00:02',
83
'0 days 00:00:03', '0 days 00:00:04'],
84
dtype='timedelta64[ns]', freq=None)
85
>>> pd.to_timedelta(np.arange(5), unit='d')
86
TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],
87
dtype='timedelta64[ns]', freq=None)
90
unit = parse_timedelta_unit(unit)
92
if errors not in ("ignore", "raise", "coerce"):
93
raise ValueError("errors must be one of 'ignore', 'raise', or 'coerce'}")
95
if unit in {"Y", "y", "M"}:
97
"Units 'M', 'Y', and 'y' are no longer supported, as they do not "
98
"represent unambiguous timedelta values durations."
103
elif isinstance(arg, ABCSeries):
104
values = _convert_listlike(arg._values, unit=unit, errors=errors)
105
return arg._constructor(values, index=arg.index, name=arg.name)
106
elif isinstance(arg, ABCIndexClass):
107
return _convert_listlike(arg, unit=unit, errors=errors, name=arg.name)
108
elif isinstance(arg, np.ndarray) and arg.ndim == 0:
109
# extract array scalar and process below
111
elif is_list_like(arg) and getattr(arg, "ndim", 1) == 1:
112
return _convert_listlike(arg, unit=unit, errors=errors)
113
elif getattr(arg, "ndim", 1) > 1:
115
"arg must be a string, timedelta, list, tuple, 1-d array, or Series"
118
if isinstance(arg, str) and unit is not None:
119
raise ValueError("unit must not be specified if the input is/contains a str")
121
# ...so it must be a scalar value. Return scalar.
122
return _coerce_scalar_to_timedelta_type(arg, unit=unit, errors=errors)
125
def _coerce_scalar_to_timedelta_type(r, unit="ns", errors="raise"):
126
"""Convert string 'r' to a timedelta object."""
128
result = Timedelta(r, unit)
130
if errors == "raise":
132
elif errors == "ignore":
141
def _convert_listlike(arg, unit=None, errors="raise", name=None):
142
"""Convert a list of objects to a timedelta index object."""
143
if isinstance(arg, (list, tuple)) or not hasattr(arg, "dtype"):
144
# This is needed only to ensure that in the case where we end up
145
# returning arg (errors == "ignore"), and where the input is a
146
# generator, we return a useful list-like instead of a
148
arg = np.array(list(arg), dtype=object)
151
value = sequence_to_td64ns(arg, unit=unit, errors=errors, copy=False)[0]
153
if errors == "ignore":
156
# This else-block accounts for the cases when errors='raise'
157
# and errors='coerce'. If errors == 'raise', these errors
158
# should be raised. If errors == 'coerce', we shouldn't
159
# expect any errors to be raised, since all parsing errors
160
# cause coercion to pd.NaT. However, if an error / bug is
161
# introduced that causes an Exception to be raised, we would
162
# like to surface it.
165
from pandas import TimedeltaIndex
167
value = TimedeltaIndex(value, unit="ns", name=name)