~teamproject/sisepeu/main

« back to all changes in this revision

Viewing changes to env/lib/python3.6/site-packages/pandas/core/tools/timedeltas.py

  • Committer: riveramarlon113 at gmail
  • Date: 2023-06-04 02:19:28 UTC
  • Revision ID: riveramarlon113@gmail.com-20230604021928-rbt05g3480tfhxxj
Correcion de cosas pequeñas

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
"""
2
 
timedelta support tools
3
 
"""
4
 
 
5
 
import numpy as np
6
 
 
7
 
from pandas._libs.tslibs import NaT
8
 
from pandas._libs.tslibs.timedeltas import Timedelta, parse_timedelta_unit
9
 
 
10
 
from pandas.core.dtypes.common import is_list_like
11
 
from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries
12
 
 
13
 
from pandas.core.arrays.timedeltas import sequence_to_td64ns
14
 
 
15
 
 
16
 
def to_timedelta(arg, unit=None, errors="raise"):
17
 
    """
18
 
    Convert argument to timedelta.
19
 
 
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.
24
 
 
25
 
    Parameters
26
 
    ----------
27
 
    arg : str, timedelta, list-like or Series
28
 
        The data to be converted to timedelta.
29
 
    unit : str, optional
30
 
        Denotes the unit of the arg for numeric `arg`. Defaults to ``"ns"``.
31
 
 
32
 
        Possible values:
33
 
 
34
 
        * 'W'
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'
42
 
 
43
 
        .. versionchanged:: 1.1.0
44
 
 
45
 
           Must not be specified when `arg` context strings and
46
 
           ``errors="raise"``.
47
 
 
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.
52
 
 
53
 
    Returns
54
 
    -------
55
 
    timedelta64 or numpy.array of timedelta64
56
 
        Output type returned if parsing succeeded.
57
 
 
58
 
    See Also
59
 
    --------
60
 
    DataFrame.astype : Cast argument to a specified dtype.
61
 
    to_datetime : Convert argument to datetime.
62
 
    convert_dtypes : Convert dtypes.
63
 
 
64
 
    Examples
65
 
    --------
66
 
    Parsing a single string to a Timedelta:
67
 
 
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')
72
 
 
73
 
    Parsing a list or array of strings:
74
 
 
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)
78
 
 
79
 
    Converting numbers by specifying the `unit` keyword argument:
80
 
 
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)
88
 
    """
89
 
    if unit is not None:
90
 
        unit = parse_timedelta_unit(unit)
91
 
 
92
 
    if errors not in ("ignore", "raise", "coerce"):
93
 
        raise ValueError("errors must be one of 'ignore', 'raise', or 'coerce'}")
94
 
 
95
 
    if unit in {"Y", "y", "M"}:
96
 
        raise ValueError(
97
 
            "Units 'M', 'Y', and 'y' are no longer supported, as they do not "
98
 
            "represent unambiguous timedelta values durations."
99
 
        )
100
 
 
101
 
    if arg is None:
102
 
        return arg
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
110
 
        arg = arg.item()
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:
114
 
        raise TypeError(
115
 
            "arg must be a string, timedelta, list, tuple, 1-d array, or Series"
116
 
        )
117
 
 
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")
120
 
 
121
 
    # ...so it must be a scalar value. Return scalar.
122
 
    return _coerce_scalar_to_timedelta_type(arg, unit=unit, errors=errors)
123
 
 
124
 
 
125
 
def _coerce_scalar_to_timedelta_type(r, unit="ns", errors="raise"):
126
 
    """Convert string 'r' to a timedelta object."""
127
 
    try:
128
 
        result = Timedelta(r, unit)
129
 
    except ValueError:
130
 
        if errors == "raise":
131
 
            raise
132
 
        elif errors == "ignore":
133
 
            return r
134
 
 
135
 
        # coerce
136
 
        result = NaT
137
 
 
138
 
    return result
139
 
 
140
 
 
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
147
 
        #  used-up generator
148
 
        arg = np.array(list(arg), dtype=object)
149
 
 
150
 
    try:
151
 
        value = sequence_to_td64ns(arg, unit=unit, errors=errors, copy=False)[0]
152
 
    except ValueError:
153
 
        if errors == "ignore":
154
 
            return arg
155
 
        else:
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.
163
 
            raise
164
 
 
165
 
    from pandas import TimedeltaIndex
166
 
 
167
 
    value = TimedeltaIndex(value, unit="ns", name=name)
168
 
    return value