U
    MZf                     @  sN  d dl mZ d dlmZ d dlmZ d dlmZ d dlmZ d dl	m
Z
mZmZmZmZmZmZmZmZ d dlZd dlZd dlmZmZ d d	lmZmZmZmZmZmZm Z m!Z!m"Z"m#Z$ d d
l%m&Z& d dl'm(Z(m)Z) d dl*m+Z+ d dl,m-Z-m.Z.m/Z/m0Z0 d dl1m2Z2 d dl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z< d dl=m>Z>m?Z? d dl@mAZA d dlBmCZCmDZDmEZE d dlFmGZG d dlHmIZI d dlJmKZK d dlLmMZMmNZNmOZO d dlPmQZQ d dlRmSZS d dlTmUZU e
rd dlVmWZW d dlXmYZY d dlZm[Z[m\Z\ eeee-f Z]ee^e_f Z`ee`ef Zaeeae]f Zbeee` ee`df e-f ZcG dd ded d!ZdG d"d# d#edd$d!Zeeeed%f Zfd&Zgdzd'd(d)d*d+Zhd{d-d.d/d0d1d2d3Zid-d(d0d4d5d6d7d8Zjd|d9d0d:d;d<d=d>Zkd}d?d5d@d;dAdBdCZldDd0d;dEdFdGZmd~d(d:d0d(dId'd'd0dJdKdLZnd0dMd0dMd;dNdOdPZod0dMd;dQdRdSZpdTdU ZqeddVdId0d0d0d(d0d(d0d0dWdXdYdZZredd[dId0d0d0d(d0d(d0d0d5dXd\dZZredd]dId0d0d0d(d0d(d0d0d^dXd_dZZrdHd$d$d$dejsdejsd`d f
dadId0d0d0d(dbd(dcdMd0dddedfdZZrdgdgdhdhdididjdjdkdkdldldmdmdmdndndndodododpZtdId0dqdrdsZudtdMdudvdwdxZvdyd3dZgZwdS )    )annotations)abc)datetime)partial)islice)	TYPE_CHECKINGCallableHashableListTuple	TypedDictUnioncastoverloadN)libtslib)
OutOfBoundsDatetime	Timedelta	Timestampastype_overflowsafeget_unit_from_dtypeiNaTis_supported_unitnat_stringsparsing	timezones)precision_from_unit)DateParseErrorguess_datetime_format)array_strptime)AnyArrayLike	ArrayLikeDateTimeErrorChoicesnpt)find_stack_level)	ensure_objectis_datetime64_dtypeis_datetime64tz_dtypeis_float
is_integeris_integer_dtypeis_list_likeis_numeric_dtype	is_scalar)ABCDataFrame	ABCSeries)notna)DatetimeArrayIntegerArrayPandasArray)
algorithms)unique)ExtensionArray)maybe_convert_dtypeobjects_to_datetime64nstz_to_dtype)extract_array)Index)DatetimeIndex)NaTType)UnitChoices)	DataFrameSeries.c                   @  s&   e Zd ZU ded< ded< ded< dS )YearMonthDayDictDatetimeDictArgyearmonthdayN__name__
__module____qualname____annotations__ rK   rK   ?/tmp/pip-unpacked-wheel-nbcvw55c/pandas/core/tools/datetimes.pyrA   k   s   
rA   T)totalc                   @  sV   e Zd ZU ded< ded< ded< ded< ded< ded< ded< ded	< ded
< dS )FulldatetimeDictrB   hourhoursminuteminutessecondsecondsmsusnsNrF   rK   rK   rK   rL   rN   q   s   
rN   Fr?   2   zbool | Nonez
str | None)dayfirstreturnc                 C  sn   t |  }dkrjt| |  }tkrjt||d}|d k	r>|S t | |d d  dkrjtjdtt d d S )NrY      zCould not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.
stacklevel)	r   first_non_nulltypestrr   warningswarnUserWarningr$   )arrrY   r`   Zfirst_non_nan_elementZguessed_formatrK   rK   rL    _guess_datetime_format_for_array   s     rg   ffffff?ArrayConvertiblefloatz
int | Nonebool)argunique_sharecheck_countrZ   c                 C  s   d}|dkr<t | tkrdS t | dkr6t | d }qjd}n.d|  krTt | ks^n td|dkrjdS d|  k r~d	k sn td
ztt| |}W n tk
r   Y dS X t ||| krd}|S )a  
    Decides whether to do caching.

    If the percent of unique elements among `check_count` elements less
    than `unique_share * 100` then we can do caching.

    Parameters
    ----------
    arg: listlike, tuple, 1-d array, Series
    unique_share: float, default=0.7, optional
        0 < unique_share < 1
    check_count: int, optional
        0 <= check_count <= len(arg)

    Returns
    -------
    do_caching: bool

    Notes
    -----
    By default for a sequence of less than 50 items in size, we don't do
    caching; for the number of elements less than 5000, we take ten percent of
    all elements to check for a uniqueness share; if the sequence size is more
    than 5000, then we check only the first 500 elements.
    All constants were chosen empirically by.
    TNFi  
   i  r   z1check_count must be in next bounds: [0; len(arg)]r]   z+unique_share must be in next bounds: (0; 1))lenstart_caching_atAssertionErrorsetr   	TypeError)rl   rm   rn   Z
do_cachingZunique_elementsrK   rK   rL   should_cache   s0     
ru   r   r@   )rl   formatcacheconvert_listlikerZ   c                 C  s   ddl m} |td}|rt| s&|S t| }t|t| k r|||}z|||dd}W n tk
rr   | Y S X |jjs||j	   }|S )a  
    Create a cache of unique dates from an array of dates

    Parameters
    ----------
    arg : listlike, tuple, 1-d array, Series
    format : string
        Strftime format to parse time
    cache : bool
        True attempts to create a cache of converted values
    convert_listlike : function
        Conversion function to apply on dates

    Returns
    -------
    cache_array : Series
        Cache of converted, unique dates. Can be empty
    r   r@   dtypeF)indexcopy)
pandasr@   objectru   r5   rp   r   r|   	is_uniqueZ
duplicated)rl   rv   rw   rx   r@   cache_arrayZunique_datesZcache_datesrK   rK   rL   _maybe_cache   s    


r   r!   r	   r;   )dt_arrayutcnamerZ   c                 C  s2   t | r"|rdnd}t| ||dS t| || jdS )a  
    Properly boxes the ndarray of datetimes to DatetimeIndex
    if it is possible or to generic Index instead

    Parameters
    ----------
    dt_array: 1-d array
        Array of datetimes to be wrapped in an Index.
    utc : bool
        Whether to convert/localize timestamps to UTC.
    name : string, default None
        Name for a resulting index

    Returns
    -------
    result : datetime of converted dates
        - DatetimeIndex if convertible to sole datetime64 type
        - general Index otherwise
    r   Ntzr   )r   r{   )r&   r<   r;   r{   )r   r   r   r   rK   rK   rL   _box_as_indexlike  s    r    DatetimeScalarOrArrayConvertiblezHashable | None)rl   r   r   rZ   c                 C  s2   ddl m} || |jjd|}t|jd|dS )a  
    Convert array of dates with a cache and wrap the result in an Index.

    Parameters
    ----------
    arg : integer, float, string, datetime, list, tuple, 1-d array, Series
    cache_array : Series
        Cache of converted, unique dates
    name : string, default None
        Name for a DatetimeIndex

    Returns
    -------
    result : Index-like of converted dates
    r   ry   rz   Fr   r   )r~   r@   r|   r{   mapr   _values)rl   r   r   r@   resultrK   rK   rL   _convert_and_box_cache#  s    r   z
np.ndarray)r   r   rZ   c                 C  sr   t jt| td}t|D ]J}||k}t| | |}|r\|jdkrR|d}n
|d}|||< qt	||dS )a  
    Return results from array_strptime if a %z or %Z directive was passed.

    Parameters
    ----------
    result : ndarray[int64]
        int64 date representations of the dates
    timezones : ndarray
        pytz timezone objects
    utc : bool
        Whether to convert/localize timestamps to UTC.
    name : string, default None
        Name for a DatetimeIndex

    Returns
    -------
    tz_result : Index-like of parsed dates with timezone
    rz   Nr   r   )
npemptyrp   r   r5   r1   tz_localizetzinfo
tz_convertr;   )r   r   r   r   Z
tz_resultszonemaskdtarK   rK   rL   _return_parsed_timezone_results=  s    


r   raiser"   )rv   r   r   uniterrorsrY   	yearfirstexactc	                 C  sR  t | ttfrtj| dd} nt | tr2t| } t| dd}	|rFdnd}
t|	rt | tt	fsnt	| |
|dS |r| 
dd} | S t|	rttj|	}	tt|	stt| td|dkd	} t | tt	fst	| |
|dS |r| dS | S |dk	r|dk	rtd
t| ||||S t| dddkr8tdzt| dt|
d\} }W nj tk
r   |dkrtjdgddt| }t	||d Y S |dkrt| |d}| Y S  Y nX t| } |dkrt| |d}|dk	r|dkrt| |||||S t| ||||dd\}}|dk	rDt|t |d}t	j!||dS t"|||dS )a  
    Helper function for to_datetime. Performs the conversions of 1D listlike
    of dates

    Parameters
    ----------
    arg : list, tuple, ndarray, Series, Index
        date to be parsed
    name : object
        None or string for the Index name
    utc : bool
        Whether to convert/localize timestamps to UTC.
    unit : str
        None or string of the frequency of the passed data
    errors : str
        error handing behaviors from to_datetime, 'raise', 'coerce', 'ignore'
    dayfirst : bool
        dayfirst parsing behavior from to_datetime
    yearfirst : bool
        yearfirst parsing behavior from to_datetime
    exact : bool, default True
        exact format matching behavior from to_datetime

    Returns
    -------
    Index-like of parsed dates
    Orz   r{   Nr   r   zM8[s]coerce)Z	is_coercez#cannot specify both format and unitndimr]   zAarg must be a string, datetime, list, tuple, 1-d array, or SeriesF)r}   r   NaTzdatetime64[ns]r   ignorer\   mixedT)rY   r   r   r   Zallow_objectr   )#
isinstancelisttupler   arrayr3   getattrr'   r1   r<   r   r   r&   r   r{   r   r   r   asarray
ValueError_to_datetime_with_unitrt   r7   libtimezonesZmaybe_get_tzrepeatrp   r;   r%   rg   _array_strptime_with_fallbackr8   r9   Z_simple_newr   )rl   rv   r   r   r   r   rY   r   r   Z	arg_dtyper   _Znpvaluesidxr   	tz_parsedr   rK   rK   rL   _convert_listlike_datetimes`  sx    &








	
r   rb   )r   fmtr   r   rZ   c                 C  sD   t | ||||d\}}tdd |D r6t||||S t|||dS )zL
    Call array_strptime, with fallback behavior depending on 'errors'.
    )r   r   r   c                 s  s   | ]}|d k	V  qd S NrK   ).0r   rK   rK   rL   	<genexpr>  s     z0_array_strptime_with_fallback.<locals>.<genexpr>r   )r   anyr   r   )rl   r   r   r   r   r   r   r   rK   rK   rL   r     s    r   )r   r   rZ   c              	   C  s
  t | dd} t| tr0| d| d}d}nht| } | jjdkr| jd| ddd}zt|td	dd}W n8 t	k
r   |d
kr | t
} t| |||| Y S X d}n| jjdkrvt|\}}t| | tkB }	| | jddd}
d|
|	< |
tjjk  s|
tjjk rR|d
krB| t
} t| ||||S t	d| d|
jd	dd}tdd||	< d}n"| jt
dd} tj| ||d\}}|dkrtj||d}nt||d}t|ts|S |d|}|r|jdkr|d}n
|d}|S )zF
    to_datetime specalized to the case where a 'unit' is passed.
    T)Zextract_numpyzdatetime64[]N)iuFr}   M8[ns]r   fZf8r   z cannot convert input with unit ''r   rW   r   r   r   UTCr   )r:   r   r2   astyper   r   r{   kindr   r   r   r   r   isnanr   r   min_valuer   maxZ
datetime64r   Zarray_with_unit_to_datetimer;   Z_with_inferr<   r   r   r   )rl   r   r   r   r   rf   r   Zmultr   r   Zfvaluesr   rK   rK   rL   r     sV    







r   c              
   C  s  |dkr| }t d }|dkr(tdz| | } W n, tk
r` } ztd|W 5 d}~X Y nX t j | }t j | }t| |kst| |k rt| dn t	| rt
| st| stt| std|  d	| d
zt ||d}W nj tk
r. } ztd| d|W 5 d}~X Y n6 tk
rb } ztd| d|W 5 d}~X Y nX |jdk	rtd| d|t d }	|	td|d }
t| rt| tttjfst| } | |
 } | S )a  
    Helper function for to_datetime.
    Adjust input argument to the specified origin

    Parameters
    ----------
    arg : list, tuple, ndarray, Series, Index
        date to be adjusted
    origin : 'julian' or Timestamp
        origin offset for the arg
    unit : str
        passed unit from to_datetime, must be 'D'

    Returns
    -------
    ndarray or scalar of adjusted date(s)
    Zjulianr   Dz$unit must be 'D' for origin='julian'z3incompatible 'arg' type for given 'origin'='julian'Nz% is Out of Bounds for origin='julian'r   z!' is not compatible with origin='z+'; it must be numeric with a unit specified)r   zorigin z is Out of Boundsz# cannot be converted to a Timestampzorigin offset z must be tz-naiver]   )r   Zto_julian_dater   rt   r   r   r   r   r   r-   r)   r(   r,   r   r   r   r+   r   r/   r;   ndarray)rl   originr   originalZj0errZj_maxZj_minoffsetZ	td_offsetZioffsetrK   rK   rL   _adjust_to_origin3  s`    "

r   DatetimeScalarr   )rl   r   rY   r   r   rv   r   r   infer_datetime_formatrw   rZ   c                 C  s   d S r   rK   rl   r   rY   r   r   rv   r   r   r   r   rw   rK   rK   rL   to_datetime|  s    r   zSeries | DictConvertiblec                 C  s   d S r   rK   r   rK   rK   rL   r     s    z list | tuple | Index | ArrayLiker<   c                 C  s   d S r   rK   r   rK   rK   rL   r     s    unixz2DatetimeScalarOrArrayConvertible | DictConvertiblezbool | lib.NoDefaultzlib.NoDefault | boolz8DatetimeIndex | Series | DatetimeScalar | NaTType | None)rl   r   rY   r   r   rv   r   r   r   r   rw   rZ   c              	   C  s&  |t jk	r|dkrtd|t jk	r4tjdt d | dkr@dS |	dkrTt| |	|} tt||||||d}t	| t
r| }|r| jdk	r| d}n
| d}nt	| trt| ||
|}|js| |}n || j|}| j|| j| jd	}n4t	| ttjfrt| ||}nt	| trVt| ||
|}|jsDt| || jd
}n|| || jd
}nt| rz.tttt t!t"j#dtf | }t|||
|}W n: t$k
r   |dkr ddl%m&} |g t'd}Y nX |jst||}n
|||}n8|t"(| g|d }t	| t)r"t	|t"j*r"t)|}|S )u5  
    Convert argument to datetime.

    This function converts a scalar, array-like, :class:`Series` or
    :class:`DataFrame`/dict-like to a pandas datetime object.

    Parameters
    ----------
    arg : int, float, str, datetime, list, tuple, 1-d array, Series, DataFrame/dict-like
        The object to convert to a datetime. If a :class:`DataFrame` is provided, the
        method expects minimally the following columns: :const:`"year"`,
        :const:`"month"`, :const:`"day"`.
    errors : {'ignore', 'raise', 'coerce'}, default 'raise'
        - If :const:`'raise'`, then invalid parsing will raise an exception.
        - If :const:`'coerce'`, then invalid parsing will be set as :const:`NaT`.
        - If :const:`'ignore'`, then invalid parsing will return the input.
    dayfirst : bool, default False
        Specify a date parse order if `arg` is str or is list-like.
        If :const:`True`, parses dates with the day first, e.g. :const:`"10/11/12"`
        is parsed as :const:`2012-11-10`.

        .. warning::

            ``dayfirst=True`` is not strict, but will prefer to parse
            with day first.

    yearfirst : bool, default False
        Specify a date parse order if `arg` is str or is list-like.

        - If :const:`True` parses dates with the year first, e.g.
          :const:`"10/11/12"` is parsed as :const:`2010-11-12`.
        - If both `dayfirst` and `yearfirst` are :const:`True`, `yearfirst` is
          preceded (same as :mod:`dateutil`).

        .. warning::

            ``yearfirst=True`` is not strict, but will prefer to parse
            with year first.

    utc : bool, default False
        Control timezone-related parsing, localization and conversion.

        - If :const:`True`, the function *always* returns a timezone-aware
          UTC-localized :class:`Timestamp`, :class:`Series` or
          :class:`DatetimeIndex`. To do this, timezone-naive inputs are
          *localized* as UTC, while timezone-aware inputs are *converted* to UTC.

        - If :const:`False` (default), inputs will not be coerced to UTC.
          Timezone-naive inputs will remain naive, while timezone-aware ones
          will keep their time offsets. Limitations exist for mixed
          offsets (typically, daylight savings), see :ref:`Examples
          <to_datetime_tz_examples>` section for details.

        See also: pandas general documentation about `timezone conversion and
        localization
        <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html
        #time-zone-handling>`_.

    format : str, default None
        The strftime to parse time, e.g. :const:`"%d/%m/%Y"`. See
        `strftime documentation
        <https://docs.python.org/3/library/datetime.html
        #strftime-and-strptime-behavior>`_ for more information on choices, though
        note that :const:`"%f"` will parse all the way up to nanoseconds.
        You can also pass:

        - "ISO8601", to parse any `ISO8601 <https://en.wikipedia.org/wiki/ISO_8601>`_
          time string (not necessarily in exactly the same format);
        - "mixed", to infer the format for each element individually. This is risky,
          and you should probably use it along with `dayfirst`.
    exact : bool, default True
        Control how `format` is used:

        - If :const:`True`, require an exact `format` match.
        - If :const:`False`, allow the `format` to match anywhere in the target
          string.

        Cannot be used alongside ``format='ISO8601'`` or ``format='mixed'``.
    unit : str, default 'ns'
        The unit of the arg (D,s,ms,us,ns) denote the unit, which is an
        integer or float number. This will be based off the origin.
        Example, with ``unit='ms'`` and ``origin='unix'``, this would calculate
        the number of milliseconds to the unix epoch start.
    infer_datetime_format : bool, default False
        If :const:`True` and no `format` is given, attempt to infer the format
        of the datetime strings based on the first non-NaN element,
        and if it can be inferred, switch to a faster method of parsing them.
        In some cases this can increase the parsing speed by ~5-10x.

        .. deprecated:: 2.0.0
            A strict version of this argument is now the default, passing it has
            no effect.

    origin : scalar, default 'unix'
        Define the reference date. The numeric values would be parsed as number
        of units (defined by `unit`) since this reference date.

        - If :const:`'unix'` (or POSIX) time; origin is set to 1970-01-01.
        - If :const:`'julian'`, unit must be :const:`'D'`, and origin is set to
          beginning of Julian Calendar. Julian day number :const:`0` is assigned
          to the day starting at noon on January 1, 4713 BC.
        - If Timestamp convertible (Timestamp, dt.datetime, np.datetimt64 or date
          string), origin is set to Timestamp identified by origin.
        - If a float or integer, origin is the millisecond difference
          relative to 1970-01-01.
    cache : bool, default True
        If :const:`True`, use a cache of unique, converted dates to apply the
        datetime conversion. May produce significant speed-up when parsing
        duplicate date strings, especially ones with timezone offsets. The cache
        is only used when there are at least 50 values. The presence of
        out-of-bounds values will render the cache unusable and may slow down
        parsing.

    Returns
    -------
    datetime
        If parsing succeeded.
        Return type depends on input (types in parenthesis correspond to
        fallback in case of unsuccessful timezone or out-of-range timestamp
        parsing):

        - scalar: :class:`Timestamp` (or :class:`datetime.datetime`)
        - array-like: :class:`DatetimeIndex` (or :class:`Series` with
          :class:`object` dtype containing :class:`datetime.datetime`)
        - Series: :class:`Series` of :class:`datetime64` dtype (or
          :class:`Series` of :class:`object` dtype containing
          :class:`datetime.datetime`)
        - DataFrame: :class:`Series` of :class:`datetime64` dtype (or
          :class:`Series` of :class:`object` dtype containing
          :class:`datetime.datetime`)

    Raises
    ------
    ParserError
        When parsing a date from string fails.
    ValueError
        When another datetime conversion error happens. For example when one
        of 'year', 'month', day' columns is missing in a :class:`DataFrame`, or
        when a Timezone-aware :class:`datetime.datetime` is found in an array-like
        of mixed time offsets, and ``utc=False``.

    See Also
    --------
    DataFrame.astype : Cast argument to a specified dtype.
    to_timedelta : Convert argument to timedelta.
    convert_dtypes : Convert dtypes.

    Notes
    -----

    Many input types are supported, and lead to different output types:

    - **scalars** can be int, float, str, datetime object (from stdlib :mod:`datetime`
      module or :mod:`numpy`). They are converted to :class:`Timestamp` when
      possible, otherwise they are converted to :class:`datetime.datetime`.
      None/NaN/null scalars are converted to :const:`NaT`.

    - **array-like** can contain int, float, str, datetime objects. They are
      converted to :class:`DatetimeIndex` when possible, otherwise they are
      converted to :class:`Index` with :class:`object` dtype, containing
      :class:`datetime.datetime`. None/NaN/null entries are converted to
      :const:`NaT` in both cases.

    - **Series** are converted to :class:`Series` with :class:`datetime64`
      dtype when possible, otherwise they are converted to :class:`Series` with
      :class:`object` dtype, containing :class:`datetime.datetime`. None/NaN/null
      entries are converted to :const:`NaT` in both cases.

    - **DataFrame/dict-like** are converted to :class:`Series` with
      :class:`datetime64` dtype. For each row a datetime is created from assembling
      the various dataframe columns. Column keys can be common abbreviations
      like [‘year’, ‘month’, ‘day’, ‘minute’, ‘second’, ‘ms’, ‘us’, ‘ns’]) or
      plurals of the same.

    The following causes are responsible for :class:`datetime.datetime` objects
    being returned (possibly inside an :class:`Index` or a :class:`Series` with
    :class:`object` dtype) instead of a proper pandas designated type
    (:class:`Timestamp`, :class:`DatetimeIndex` or :class:`Series`
    with :class:`datetime64` dtype):

    - when any input element is before :const:`Timestamp.min` or after
      :const:`Timestamp.max`, see `timestamp limitations
      <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html
      #timeseries-timestamp-limits>`_.

    - when ``utc=False`` (default) and the input is an array-like or
      :class:`Series` containing mixed naive/aware datetime, or aware with mixed
      time offsets. Note that this happens in the (quite frequent) situation when
      the timezone has a daylight savings policy. In that case you may wish to
      use ``utc=True``.

    Examples
    --------

    **Handling various input formats**

    Assembling a datetime from multiple columns of a :class:`DataFrame`. The keys
    can be common abbreviations like ['year', 'month', 'day', 'minute', 'second',
    'ms', 'us', 'ns']) or plurals of the same

    >>> df = pd.DataFrame({'year': [2015, 2016],
    ...                    'month': [2, 3],
    ...                    'day': [4, 5]})
    >>> pd.to_datetime(df)
    0   2015-02-04
    1   2016-03-05
    dtype: datetime64[ns]

    Using a unix epoch time

    >>> pd.to_datetime(1490195805, unit='s')
    Timestamp('2017-03-22 15:16:45')
    >>> pd.to_datetime(1490195805433502912, unit='ns')
    Timestamp('2017-03-22 15:16:45.433502912')

    .. warning:: For float arg, precision rounding might happen. To prevent
        unexpected behavior use a fixed-width exact type.

    Using a non-unix epoch origin

    >>> pd.to_datetime([1, 2, 3], unit='D',
    ...                origin=pd.Timestamp('1960-01-01'))
    DatetimeIndex(['1960-01-02', '1960-01-03', '1960-01-04'],
                  dtype='datetime64[ns]', freq=None)

    **Differences with strptime behavior**

    :const:`"%f"` will parse all the way up to nanoseconds.

    >>> pd.to_datetime('2018-10-26 12:00:00.0000000011',
    ...                format='%Y-%m-%d %H:%M:%S.%f')
    Timestamp('2018-10-26 12:00:00.000000001')

    **Non-convertible date/times**

    If a date does not meet the `timestamp limitations
    <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html
    #timeseries-timestamp-limits>`_, passing ``errors='ignore'``
    will return the original input instead of raising any exception.

    Passing ``errors='coerce'`` will force an out-of-bounds date to :const:`NaT`,
    in addition to forcing non-dates (or non-parseable dates) to :const:`NaT`.

    >>> pd.to_datetime('13000101', format='%Y%m%d', errors='ignore')
    '13000101'
    >>> pd.to_datetime('13000101', format='%Y%m%d', errors='coerce')
    NaT

    .. _to_datetime_tz_examples:

    **Timezones and time offsets**

    The default behaviour (``utc=False``) is as follows:

    - Timezone-naive inputs are converted to timezone-naive :class:`DatetimeIndex`:

    >>> pd.to_datetime(['2018-10-26 12:00:00', '2018-10-26 13:00:15'])
    DatetimeIndex(['2018-10-26 12:00:00', '2018-10-26 13:00:15'],
                  dtype='datetime64[ns]', freq=None)

    - Timezone-aware inputs *with constant time offset* are converted to
      timezone-aware :class:`DatetimeIndex`:

    >>> pd.to_datetime(['2018-10-26 12:00 -0500', '2018-10-26 13:00 -0500'])
    DatetimeIndex(['2018-10-26 12:00:00-05:00', '2018-10-26 13:00:00-05:00'],
                  dtype='datetime64[ns, UTC-05:00]', freq=None)

    - However, timezone-aware inputs *with mixed time offsets* (for example
      issued from a timezone with daylight savings, such as Europe/Paris)
      are **not successfully converted** to a :class:`DatetimeIndex`. Instead a
      simple :class:`Index` containing :class:`datetime.datetime` objects is
      returned:

    >>> pd.to_datetime(['2020-10-25 02:00 +0200', '2020-10-25 04:00 +0100'])
    Index([2020-10-25 02:00:00+02:00, 2020-10-25 04:00:00+01:00],
          dtype='object')

    - A mix of timezone-aware and timezone-naive inputs is also converted to
      a simple :class:`Index` containing :class:`datetime.datetime` objects:

    >>> from datetime import datetime
    >>> pd.to_datetime(["2020-01-01 01:00:00-01:00", datetime(2020, 1, 1, 3, 0)])
    Index([2020-01-01 01:00:00-01:00, 2020-01-01 03:00:00], dtype='object')

    |

    Setting ``utc=True`` solves most of the above issues:

    - Timezone-naive inputs are *localized* as UTC

    >>> pd.to_datetime(['2018-10-26 12:00', '2018-10-26 13:00'], utc=True)
    DatetimeIndex(['2018-10-26 12:00:00+00:00', '2018-10-26 13:00:00+00:00'],
                  dtype='datetime64[ns, UTC]', freq=None)

    - Timezone-aware inputs are *converted* to UTC (the output represents the
      exact same datetime, but viewed from the UTC time offset `+00:00`).

    >>> pd.to_datetime(['2018-10-26 12:00 -0530', '2018-10-26 12:00 -0500'],
    ...                utc=True)
    DatetimeIndex(['2018-10-26 17:30:00+00:00', '2018-10-26 17:00:00+00:00'],
                  dtype='datetime64[ns, UTC]', freq=None)

    - Inputs can contain both string or datetime, the above
      rules still apply

    >>> pd.to_datetime(['2018-10-26 12:00', datetime(2020, 1, 1, 18)], utc=True)
    DatetimeIndex(['2018-10-26 12:00:00+00:00', '2020-01-01 18:00:00+00:00'],
                  dtype='datetime64[ns, UTC]', freq=None)
    >   ISO8601r   z8Cannot use 'exact' when 'format' is 'mixed' or 'ISO8601'zThe argument 'infer_datetime_format' is deprecated and will be removed in a future version. A strict version of it is now the default, see https://pandas.pydata.org/pdeps/0004-consistent-to-datetime-parsing.html. You can safely remove this argument.r^   Nr   )r   r   rY   r   r   r   r   )r|   r   r   r@   r   r   ry   rz   )+r   
no_defaultr   rc   rd   r$   r   r   r   r   r   r   r   r   r/   r   r   r   r   Z_constructorr|   r   r.   r   MutableMapping_assemble_from_unit_mappingsr;   r   r+   r   r   r   r   r6   r   r   r   r~   r@   r   r   rk   Zbool_)rl   r   rY   r   r   rv   r   r   r   r   rw   rx   r   r   valuesZargcr@   rK   rK   rL   r     sx      D




 
rC   rD   rE   hmsrU   rV   rW   )rC   ZyearsrD   monthsrE   daysrO   rP   rQ   rR   rS   rT   rU   ZmillisecondZmillisecondsrV   microsecondmicrosecondsrW   Z
nanosecondZnanoseconds)r   r   c                   s  ddl m}mm} || } | jjs,tddd fdd|  D }dd | D }d	d
dg}t	t
|t
|  }t|rd|}	td|	 dt	t
| t
t  }
t|
rd|
}td| d fdd}|| |d	  d || |d
  d  || |d   }zt|d |d}W n8 ttfk
rp } ztd| |W 5 d}~X Y nX ddddddg}|D ]}||}|dk	r|| krz|||| | | d7 }W n> ttfk
r } ztd | d!| |W 5 d}~X Y nX q|S )"a.  
    assemble the unit specified fields from the arg (DataFrame)
    Return a Series for actual parsing

    Parameters
    ----------
    arg : DataFrame
    errors : {'ignore', 'raise', 'coerce'}, default 'raise'

        - If :const:`'raise'`, then invalid parsing will raise an exception
        - If :const:`'coerce'`, then invalid parsing will be set as :const:`NaT`
        - If :const:`'ignore'`, then invalid parsing will return the input
    utc : bool
        Whether to convert/localize timestamps to UTC.

    Returns
    -------
    Series
    r   )r?   
to_numericto_timedeltaz#cannot assemble with duplicate keysc                 S  s,   | t krt |  S |  t kr(t |   S | S r   )	_unit_maplower)valuerK   rK   rL   r     s
    z'_assemble_from_unit_mappings.<locals>.fc                   s   i | ]}| |qS rK   rK   )r   k)r   rK   rL   
<dictcomp>  s      z0_assemble_from_unit_mappings.<locals>.<dictcomp>c                 S  s   i | ]\}}||qS rK   rK   )r   r   vrK   rK   rL   r     s      rC   rD   rE   ,zNto assemble mappings requires at least that [year, month, day] be specified: [z] is missingz9extra keys have been passed to the datetime assemblage: [r   c                   s&   |  d} t | r"| jddd} | S )Nr   int64Fr   )r*   r   )r   )r   r   rK   rL   r     s    z,_assemble_from_unit_mappings.<locals>.coerce'  d   z%Y%m%d)rv   r   r   zcannot assemble the datetimes: Nr   r   r   rU   rV   rW   )r   r   zcannot assemble the datetimes [z]: )r~   r?   r   r   columnsr   r   keysitemssortedrs   rp   joinr   r   r   rt   get)rl   r   r   r?   r   r   Zunit_revrequiredreqZ	_requiredZexcessZ_excessr   r   r   Zunitsr   r   rK   )r   r   r   rL   r   `  sX    






"
r   znpt.NDArray[np.object_]znp.ndarray | None)rl   r   rZ   c              
     s   fdd  fdd}z |  tjW S  tttfk
rD   Y nX z|  tj}||t|W S  tttfk
r|   Y nX zt	| t
t }|| |W S  tttfk
r   Y nX dS )a*  
    try to parse the YYYYMMDD/%Y%m%d format, try to deal with NaT-like,
    arg is a passed in as an object dtype, but could really be ints/strings
    with nan-like/or floats (e.g. with nan)

    Parameters
    ----------
    arg : np.ndarray[object]
    errors : {'raise','ignore','coerce'}
    c                   s>   | j tdd} t| d | d d | d }tj| dd S )NFr   r   r   r   r   )r   r   r   Ztry_parse_year_month_dayr   Zarray_to_datetime)cargparsedr   rK   rL   calc  s     
 z_attempt_YYYYMMDD.<locals>.calcc                   sR   t j| jdd}|d}t|| <  | | t jt j}|d||< |S )Nr   rz   i8)r   r   shapeviewr   r   float64r   )r   r   r   ZiresultZmasked_result)r   rK   rL   calc_with_mask  s    

z)_attempt_YYYYMMDD.<locals>.calc_with_maskN)r   r   r   r   OverflowErrorrt   r   r0   r4   isinr   r   )rl   r   r   r   r   rK   )r   r   rL   _attempt_YYYYMMDD  s"    
r   r   )F)rh   N)FN)N)NFNr   NNT)
..........)
..........)
..........)x
__future__r   collectionsr   r   	functoolsr   	itertoolsr   typingr   r   r	   r
   r   r   r   r   r   rc   Znumpyr   Zpandas._libsr   r   Zpandas._libs.tslibsr   r   r   r   r   r   r   r   r   r   r   Zpandas._libs.tslibs.conversionr   Zpandas._libs.tslibs.parsingr   r   Zpandas._libs.tslibs.strptimer   Zpandas._typingr    r!   r"   r#   Zpandas.util._exceptionsr$   Zpandas.core.dtypes.commonr%   r&   r'   r(   r)   r*   r+   r,   r-   Zpandas.core.dtypes.genericr.   r/   Zpandas.core.dtypes.missingr0   Zpandas.arraysr1   r2   r3   Zpandas.corer4   Zpandas.core.algorithmsr5   Zpandas.core.arrays.baser6   Zpandas.core.arrays.datetimesr7   r8   r9   Zpandas.core.constructionr:   Zpandas.core.indexes.baser;   Zpandas.core.indexes.datetimesr<   Zpandas._libs.tslibs.nattyper=   Zpandas._libs.tslibs.timedeltasr>   r~   r?   r@   ri   rj   rb   ZScalarr   r   rB   rA   rN   ZDictConvertiblerq   rg   ru   r   r   r   r   r   r   r   r   r   r   r   r   r   __all__rK   rK   rK   rL   <module>   s  ,0,   <0     &       yHI          &          &          &&   ^7