a
    DBìjVª  ã                   @  s  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 d dlZd dlZd dlmZ d d	lmZmZ d d
l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+ d dl,m-Z- d dl.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4 d dl5m6Z6m7Z7 d dl8m9Z9m:Z: d dl;m<Z<m=Z=m>Z> d dl?m@Z@ d dlAmBZB d dlCmDZD d dlEmFZFmGZGmHZH d dlImJZJ d dlKmLZL d dlMmNZN e�rÚd dlOmPZP d dlQmRZR d dlSmTZT d dlUmVZVmWZW eeXeYe)f ZZee[e\f Z]ee]eej^f Z_ee_eZf Z`eeXe] eYe]df e)f ZaG d d!„ d!ed"d#�ZbG d$d%„ d%ebd&d#�Zceecd'f Zdd(Zedrd)d*d+œd,d-„Zfdsd/d0d1d2d3œd4d5„Zgd/d*d2d6d7d8œd9d:„Zhdtd;d2d<d=d>œd?d@„ZidudAd7d<d=dBœdCdD„Zjdvd*d<d2d*dFd)d)d2dGœdHdI„Zkd2dJd2dJd=dKœdLdM„Zld2dJd=dNœdOdP„ZmdQdR„ ZnedwdSdFd2d2d2d*d2d*d2d2dTdUœdVdW„ƒZoedxdXdFd2d2d2d*d2d*d2d2d7dUœdYdW„ƒZoedydZdFd2d2d2d*d2d*d2d2d[dUœd\dW„ƒZodEd&d&d&dejpdejpd]d"f
d^dFd2d2d2d*d_d*d`dJd2dadbœdcdW„ZodddddededfdfdgdgdhdhdididjdjdjdkdkdkdldldldmœZqdFd2dnœdodp„Zrg dq¢ZsdS )zé    )Úannotations)Úabc)Údate)Úpartial)Úislice)ÚTYPE_CHECKINGÚCallableÚ	TypedDictÚUnionÚcastÚoverloadN)Úusing_string_dtype)ÚlibÚtslib)ÚOutOfBoundsDatetimeÚ	TimedeltaÚ	TimestampÚastype_overflowsafeÚis_supported_dtypeÚ	timezones)Úcast_from_unit_vectorized)ÚDateParseErrorÚguess_datetime_format)Úarray_strptime)ÚAnyArrayLikeÚ	ArrayLikeÚDateTimeErrorChoices)Úfind_stack_level)Úensure_objectÚis_floatÚ
is_integerÚis_integer_dtypeÚis_list_likeÚis_numeric_dtype)Ú
ArrowDtypeÚDatetimeTZDtype)ÚABCDataFrameÚ	ABCSeries)ÚDatetimeArrayÚIntegerArrayÚNumpyExtensionArray)Úunique)ÚArrowExtensionArray)ÚExtensionArray)Úmaybe_convert_dtypeÚobjects_to_datetime64Útz_to_dtype)Úextract_array)ÚIndex)ÚDatetimeIndex)ÚHashable)Ú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__© rC   rC   úZ/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/pandas/core/tools/datetimes.pyr9   g   s   
r9   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 )ÚFulldatetimeDictr:   ÚhourÚhoursÚminuteÚminutesÚsecondÚsecondsÚmsÚusÚnsNr>   rC   rC   rC   rD   rF   m   s   
rF   Fr7   é2   zbool | Nonez
str | None)ÚdayfirstÚreturnc                 C  sn   t  | ¡ }dkrjt| |  }ƒtu rjt||d�}|d ur>|S t  | |d d … ¡dkrjtjdttƒ d� d S )Néÿÿÿÿ©rQ   é   zªCould 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   )ÚarrrQ   rX   Zfirst_non_nan_elementZguessed_formatrC   rC   rD   Ú _guess_datetime_format_for_array€   s    ÿûr_   çffffffæ?ÚArrayConvertibleÚfloatz
int | NoneÚbool)ÚargÚunique_shareÚcheck_countrR   c                 C  sÈ   d}|du r<t | ƒtkrdS t | ƒdkr6t | ƒd }qjd}n.d|  krTt | ƒks^n J dƒ‚|dkrjdS d|  k r~d	k sˆn J d
ƒ‚ztt| |ƒƒ}W n ty®   Y dS 0 t |ƒ|| krÄd}|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)]rU   z+unique_share must be in next bounds: (0; 1))ÚlenÚstart_caching_atÚsetr   Ú	TypeError)rd   re   rf   Z
do_cachingZunique_elementsrC   rC   rD   Úshould_cache—   s.    ÿÿ
þrl   r   r8   )rd   ÚformatÚcacheÚconvert_listlikerR   c                 C  s¬   ddl m} |td�}|r¨t| ƒs&|S t| tjttt	fƒsDt 
| ¡} t| ƒ}t|ƒt| ƒk r¨|||ƒ}z|||dd�}W n tyŽ   | Y S 0 |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   ©r8   ©ÚdtypeF)ÚindexÚcopy)Úpandasr8   Úobjectrl   Ú
isinstanceÚnpÚndarrayr-   r2   r'   Úarrayr+   rh   r   rs   Ú	is_uniqueZ
duplicated)rd   rm   rn   ro   r8   Úcache_arrayZunique_datesZcache_datesrC   rC   rD   Ú_maybe_cacheÓ   s"    



r}   r   zHashable | Noner2   )Údt_arrayÚutcÚnamerR   c                 C  s8   t  | jd¡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
    ÚMr   N©Útzr€   )r€   rr   )r   Úis_np_dtyperr   r3   r2   )r~   r   r€   rƒ   rC   rC   rD   Ú_box_as_indexlike  s    r…   Ú DatetimeScalarOrArrayConvertible)rd   r|   r€   rR   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   rp   rq   F©r   r€   )ru   r8   rs   rr   Úmapr…   Ú_values)rd   r|   r€   r8   ÚresultrC   rC   rD   Ú_convert_and_box_cache"  s    r‹   Úraiser   )rm   r€   r   ÚunitÚerrorsrQ   Ú	yearfirstÚexactc	                 C  s  t | ttfƒrtj| dd�} nt | tƒr2t | ¡} t| ddƒ}	|rFdnd}
t |	tƒrˆt | tt	fƒspt	| |
|d�S |r„|  
d¡ d¡} | S t |	tƒ�r|	jtu �r|�rt | tƒrètt| jƒ}|	jjdurÔ| d¡}n
| d¡}t|ƒ} n$|	jjdu�r|  d¡} n
|  d¡} | S t |	d¡�rxt|	ƒ�sFtt | ¡t d	¡|d
kd�} t | tt	fƒ�sdt	| |
|d�S |�rt|  d¡S | S |du�r¤|du�r”tdƒ‚t| ||||ƒS t| ddƒdk�r¾tdƒ‚zt| dt  !|
¡d�\} }W nh t�yB   |d
k�rtjdgdd� "t#| ƒ¡}t	||d� Y S |dk�r<t| |d�}| Y S ‚ Y n0 t$| ƒ} |du �rbt%| |d�}|du�rˆ|dk�rˆt&| |||||ƒS t'| ||||dd�\}}|du�rút (|j¡d }ttt)||ƒƒ}| *d|j+› d�¡}tj,||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
    ÚOrq   rr   Nr   r‚   ÚUTCr�   zM8[s]Úcoerce)Z	is_coercez#cannot specify both format and unitÚndimrU   zAarg must be a string, datetime, list, tuple, 1-d array, or SeriesF)rt   rƒ   ZNaTzdatetime64[ns]©r€   ÚignorerT   ÚmixedT)rQ   r�   r   rŽ   Zallow_objectr   úM8[ú]r‡   ).rw   ÚlistÚtuplerx   rz   r*   Úgetattrr%   r(   r3   Ú
tz_convertÚtz_localizer$   rY   r   r2   r   r,   Zpyarrow_dtyperƒ   Z_dt_tz_convertZ_dt_tz_localizer   r„   r   r   Úasarrayrr   Ú
ValueErrorÚ_to_datetime_with_unitrk   r.   ÚlibtimezonesZmaybe_get_tzÚrepeatrh   r   r_   Ú_array_strptime_with_fallbackr/   Údatetime_datar0   Úviewr�   Ú_simple_newr…   )rd   rm   r€   r   r�   rŽ   rQ   r�   r�   Z	arg_dtyperƒ   Z	arg_arrayÚ_ZnpvaluesÚidxrŠ   Ú	tz_parsedZout_unitrr   Zdt64_valuesÚdtarC   rC   rD   Ú_convert_listlike_datetimes<  s”    &







ü


ÿ


ú
	
r¬   rZ   )r   Úfmtr�   rŽ   rR   c                 C  sÒ   t | ||||d�\}}|durbt |j¡d }t||d�}	tj||	d�}
|rV|
 d¡}
t|
|d�S |jt	krš|ršt |j¡d }t|d|› d	�|d
�}|S t
ƒ rÂ|jt	krÂt |¡rÂt|d|d
�S t||j|d
�S )zL
    Call array_strptime, with fallback behavior depending on 'errors'.
    )r�   rŽ   r   Nr   )rƒ   r�   rq   r’   r•   r˜   z, UTC])rr   r€   rZ   )r   rx   r¥   rr   r%   r(   r§   r�   r2   rv   r   r   Zis_string_array)rd   r€   r   r­   r�   rŽ   rŠ   Ztz_outr�   rr   r«   ÚresrC   rC   rD   r¤   Ê  s     

r¤   )r   rŽ   rR   c              
   C  sú  t | dd�} t| tƒr0|  d|› d�¡}d}�nXt | ¡} | jjdv r²| jd|› d�dd�}zt|t d	¡dd�}W n6 t	yª   |d
krŒ‚ |  t
¡} t| ||||ƒ Y S 0 d}nÖ| jjdk�rftjd
d��x zt| |d�}W nV t	�y4   |d
k�r t|  t
¡||||ƒ Y W  d  ƒ S t	d|› d�ƒ‚Y n0 W d  ƒ n1 �sL0    Y  | d	¡}d}n"| jt
dd�} tj| ||d�\}}|dk�r¢tj||d�}nt||d�}t|tƒ�s¾|S | d¡ |¡}|�rö|jdu �rì| d¡}n
| d¡}|S )zF
    to_datetime specalized to the case where a 'unit' is passed.
    T)Zextract_numpyzdatetime64[r™   NÚiuF©rt   zM8[ns]rŒ   Úf)Zover©r�   z cannot convert input with unit 'ú'©rŽ   r–   r•   r’   r   )r1   rw   r)   Úastyperx   rŸ   rr   Úkindr   r   rv   r¡   Zerrstater   r¦   r   Zarray_with_unit_to_datetimer2   Z_with_inferr3   rž   r�   rƒ   )rd   r�   r€   r   rŽ   r^   rª   rŠ   rC   rC   rD   r¡   ç  sT    



ÿ
ÿ*


r¡   c              
   C  sÎ  |dkr®| }t dƒ ¡ }|dkr(tdƒ‚z| | } W n. tyb } ztdƒ|‚W Y d}~n
d}~0 0 t j ¡ | }t j ¡ | }t | |k¡sœt | |k ¡rªt|› d�ƒ‚�nt	| ƒsât
| ƒsâtt | ¡ƒsâtd| › d	|› d
�ƒ‚zt ||d�}W nn t�y* } ztd|› d�ƒ|‚W Y d}~n@d}~0  t�y` } ztd|› d�ƒ|‚W Y d}~n
d}~0 0 |jdu�r~td|› d�ƒ‚|t dƒ }	|	td|d� }
t| ƒ�rÂt| tttjfƒ�sÂt | ¡} | |
 } | 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 specifiedr²   zorigin z is Out of Boundsz# cannot be converted to a Timestampzorigin offset z must be tz-naiverU   )r   Zto_julian_dater    rk   ÚmaxÚminrx   Úanyr   r    r   r#   rŸ   rƒ   r   r"   rw   r'   r2   ry   )rd   Úoriginr�   ÚoriginalZj0ÚerrZj_maxZj_minÚoffsetZ	td_offsetZioffsetrC   rC   rD   Ú_adjust_to_origin+  s\    ÿþÿÿÿÿÿ&
ÿþ
r¿   ÚDatetimeScalarr   )rd   rŽ   rQ   r�   r   rm   r�   r�   Úinfer_datetime_formatrn   rR   c                 C  s   d S ©NrC   ©rd   rŽ   rQ   r�   r   rm   r�   r�   rÁ   r»   rn   rC   rC   rD   Úto_datetimes  s    rÄ   zSeries | DictConvertiblec                 C  s   d S rÂ   rC   rÃ   rC   rC   rD   rÄ   „  s    z list | tuple | Index | ArrayLiker3   c                 C  s   d S rÂ   rC   rÃ   rC   rC   rD   rÄ   •  s    Úunixz2DatetimeScalarOrArrayConvertible | DictConvertiblezbool | lib.NoDefaultzlib.NoDefault | boolz8DatetimeIndex | Series | DatetimeScalar | NaTType | None)rd   rŽ   rQ   r�   r   rm   r�   r�   rÁ   r»   rn   rR   c              	   C  s@  |t jur|dv rtdƒ‚|t jur4tjdtƒ d� |dkrNtjdttƒ d� | du rZdS |	dkrnt| |	|ƒ} tt	||||||d	�}t
| tƒrº| }|r¶| jdur¬|  d
¡}n
|  d
¡}�n‚t
| tƒ�r
t| ||
|ƒ}|jsæ|  |¡}n || j|ƒ}| j|| j| jd�}�n2t
| ttjfƒ�r,t| ||ƒ}�nt
| tƒ�rrt| ||
|ƒ}|j�s`t| || jd�}n|| || jd�}nÊt| ƒ�rz.ttt t!t"t#j$dtf | ƒ}t|||
|ƒ}W n8 t%�yâ   |dk�rÆ‚ ddl&m'} |g t(d�}Y n0 |j�søt||ƒ}n
|||ƒ}n8|t# )| g¡|ƒd }t
| t*ƒ�r<t
|t#j+ƒ�r<t*|ƒ}|S )a7:  
    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"`. The column "year"
        must be specified in 4-digit format.
    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.

        .. warning::

            In a future version of pandas, parsing datetimes with mixed time
            zones will raise an error unless `utc=True`.
            Please specify `utc=True` to opt in to the new behaviour
            and silence this warning. To create a `Series` with mixed offsets and
            `object` dtype, please use `apply` and `datetime.datetime.strptime`.

        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`.

        .. note::

            If a :class:`DataFrame` is passed, then `format` has no effect.

    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 difference
          (in units determined by the ``unit`` argument) 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**

    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='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`.
      Parsing datetimes with mixed time zones will show a warning unless
      `utc=True`. If you specify `utc=False` the warning below will be shown
      and a simple :class:`Index` containing :class:`datetime.datetime`
      objects will be returned:

    >>> pd.to_datetime(['2020-10-25 02:00 +0200',
    ...                 '2020-10-25 04:00 +0100'])  # doctest: +SKIP
    FutureWarning: In a future version of pandas, parsing datetimes with mixed
    time zones will raise an error unless `utc=True`. Please specify `utc=True`
    to opt in to the new behaviour and silence this warning. To create a `Series`
    with mixed offsets and `object` dtype, please use `apply` and
    `datetime.datetime.strptime`.
    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)])  # doctest: +SKIP
    FutureWarning: In a future version of pandas, parsing datetimes with mixed
    time zones will raise an error unless `utc=True`. Please specify `utc=True`
    to opt in to the new behaviour and silence this warning. To create a `Series`
    with mixed offsets and `object` dtype, please use `apply` and
    `datetime.datetime.strptime`.
    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)
    >   ZISO8601r—   z8Cannot use 'exact' when 'format' is 'mixed' or 'ISO8601'zùThe 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.rV   r–   z’errors='ignore' is deprecated and will raise in a future version. Use to_datetime without passing `errors` and catch exceptions explicitly insteadNrÅ   )r   r�   rQ   r�   rŽ   r�   r   )rs   r€   r•   r8   rŒ   r   rp   rq   ),r   Ú
no_defaultr    r[   r\   r   ÚFutureWarningr¿   r   r¬   rw   r   rƒ   r�   rž   r'   r}   Úemptyrˆ   r‰   Z_constructorrs   r€   r&   r   ÚMutableMappingÚ_assemble_from_unit_mappingsr2   r‹   r"   r   r
   rš   r›   r-   rx   ry   r   ru   r8   rv   rz   rc   Zbool_)rd   rŽ   rQ   r�   r   rm   r�   r�   rÁ   r»   rn   ro   rŠ   r|   ÚvaluesZargcr8   rC   rC   rD   rÄ   ¦  s‚      Y
úûù


ÿ
r;   r<   r=   ÚhÚmÚsrM   rN   rO   )r;   Zyearsr<   Úmonthsr=   ÚdaysrG   rH   rI   rJ   rK   rL   rM   ZmillisecondZmillisecondsrN   ÚmicrosecondÚmicrosecondsrO   Z
nanosecondÚ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 ƒ}g d	¢}t	t
|ƒt
| ¡ ƒ ƒ}t|ƒržd
 |¡}	td|	› d�ƒ‚t	t
| ¡ ƒt
t ¡ ƒ ƒ}
t|
ƒrÜd
 |
¡}td|› d�ƒ‚‡ ‡fdd„}|| |d  ƒd || |d  ƒd  || |d  ƒ }zt|dˆ |d�}W n: ttf�yp } ztd|› �ƒ|‚W Y d}~n
d}~0 0 g d¢}|D ]„}| |¡}|du�r~|| v �r~z|||| | ƒ|ˆ d�7 }W n@ ttf�yþ } z"td|› d|› �ƒ|‚W Y d}~n
d}~0 0 �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   )r7   Ú
to_numericÚto_timedeltaz#cannot assemble with duplicate keysc                 S  s,   | t v rt |  S |  ¡ t v r(t |  ¡  S | S rÂ   )Ú	_unit_mapÚlower)ÚvaluerC   rC   rD   r±   •  s
    z'_assemble_from_unit_mappings.<locals>.fc                   s   i | ]}|ˆ |ƒ“qS rC   rC   )Ú.0Úk)r±   rC   rD   Ú
<dictcomp>Ÿ  ó    z0_assemble_from_unit_mappings.<locals>.<dictcomp>c                 S  s   i | ]\}}||“qS rC   rC   )rÙ   rÚ   ÚvrC   rC   rD   rÛ      rÜ   )r;   r<   r=   ú,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 | jƒr$| jddd�} | S )Nr´   Zint64Fr°   )r!   rr   rµ   )rË   )rŽ   rÔ   rC   rD   r“   ´  s    
z,_assemble_from_unit_mappings.<locals>.coercer;   i'  r<   éd   r=   z%Y%m%d)rm   rŽ   r   zcannot assemble the datetimes: N)rÌ   rÍ   rÎ   rM   rN   rO   )r�   rŽ   zcannot assemble the datetimes [z]: )ru   r7   rÔ   rÕ   Úcolumnsr{   r    ÚkeysÚitemsÚsortedrj   rh   ÚjoinrÖ   rË   rÄ   rk   Úget)rd   rŽ   r   r7   rÕ   r�   Zunit_revÚrequiredÚreqZ	_requiredÚexcessZ_excessr“   rË   r½   ZunitsÚurØ   rC   )rŽ   r±   rÔ   rD   rÊ   v  s\    

ÿÿ

ÿ
ÿþÿ&
ÿþrÊ   )r   rl   rÄ   )F)r`   N)FN)N)NFNrŒ   NNT)
..........)
..........)
..........)tÚ
__future__r   Úcollectionsr   Údatetimer   Ú	functoolsr   Ú	itertoolsr   Útypingr   r   r	   r
   r   r   r[   Únumpyrx   Zpandas._configr   Zpandas._libsr   r   Zpandas._libs.tslibsr   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   Zpandas.util._exceptionsr   Zpandas.core.dtypes.commonr   r   r    r!   r"   r#   Zpandas.core.dtypes.dtypesr$   r%   Zpandas.core.dtypes.genericr&   r'   Zpandas.arraysr(   r)   r*   Zpandas.core.algorithmsr+   Zpandas.core.arraysr,   Zpandas.core.arrays.baser-   Zpandas.core.arrays.datetimesr.   r/   r0   Zpandas.core.constructionr1   Zpandas.core.indexes.baser2   Zpandas.core.indexes.datetimesr3   Úcollections.abcr4   Zpandas._libs.tslibs.nattyper5   Zpandas._libs.tslibs.timedeltasr6   ru   r7   r8   rš   r›   ra   rb   rZ   ZScalarZ
datetime64rÀ   r†   r:   r9   rF   ZDictConvertibleri   r_   rl   r}   r…   r‹   r¬   r¤   r¡   r¿   rÄ   rÆ   rÖ   rÊ   Ú__all__rC   rC   rC   rD   Ú<module>   s      ÿ<3 ÿ  ý       ÷ DH          õ&          õ&          õ&õ&   ;ë^