
    Piܣ              
         U 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mZ d d	l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+ d dl,m-Z- d dl.m/Z/ d dl0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 d dl8m9Z9m:Z: d dl;m<Z<m=Z= d dl>m?Z?m@Z@mAZA d dlBmCZC d dlDmEZE d dlFmGZG d dlHmIZImJZJmKZK d dlLmMZM d dlNmOZO d dlPmQZQ er"d dlRmSZSmTZT d dlUmVZV d dlWmXZX d dl(mYZY d dlZm[Z[m\Z\ e]e^z  e)z  Z_d e`d!<   eaebz  Zcd e`d"<   ecez  ejd        z  Zed e`d#<   eee_z  Zfd e`d$<   e]ec         e^ecd%f         z  e)z  Zgd e`d&<    G d' d(ed)*          Zh G d+ d,ehd-*          Zieeid.f         Zjd/Zkd~dd4Zl	 ddd<ZmddBZn	 dddIZo	 dddKZp	 	 	 	 	 	 	 dddRZqddUZrddVZsdW Zte	 	 	 	 	 	 	 	 	 dddY            Zue	 	 	 	 	 	 	 	 	 ddd[            Zue	 	 	 	 	 	 	 	 	 ddd^            Zu e-d_          dLd-d-d-dejv        dd`d)f	dde            Zui dfdfdgdfdhdhdidhdjdjdkdjdldmdndmdodpdqdpdrdsdtdsdududvdudwdudxdxdydxdxdzdzdzd{Zwdd|Zxg d}ZydS )    )annotations)abc)date)partial)islice)TYPE_CHECKING	TypeAlias	TypedDictUnioncastoverloadN)libtslib)NaTOutOfBoundsDatetime	Timedelta	Timestampastype_overflowsafeget_supported_dtypeis_supported_dtype	timezones)cast_from_unit_vectorized)DateParseErrorguess_datetime_format)array_strptime)AnyArrayLike	ArrayLikeDateTimeErrorChoices)
set_module)find_stack_level)ensure_objectis_floatis_float_dtype
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)CallableHashable)NaTType)UnitChoices)TimeUnit)	DataFrameSeriesr	   ArrayConvertibleScalarDatetimeScalar DatetimeScalarOrArrayConvertible.DatetimeDictArgc                  .    e Zd ZU ded<   ded<   ded<   dS )YearMonthDayDictrC   yearmonthdayN__name__
__module____qualname____annotations__     o/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/pandas/core/tools/datetimes.pyrE   rE   l   s6         rO   rE   T)totalc                  j    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 )FulldatetimeDictrC   hourhoursminuteminutessecondsecondsmsusnsNrI   rN   rO   rP   rS   rS   r   s~         rO   rS   Fr=   2   dayfirstbool | Nonereturn
str | Nonec                6   t          j        |           x}dk    r~t          | |         x}          t          u r`t	          ||          }||S t          j        | |dz   d                    dk    r(t          j        dt          t                                 d S )Nr^      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    )arrr^   rg   first_non_nan_elementguessed_formats        rP    _guess_datetime_format_for_arrayrp      s    .s333::^)<<%==DD2%  N )%% #C(:(<(<$=>>"DDK  /11    4rO   ffffff?argunique_sharefloatcheck_count
int | Noneboolc                   d}|Ct          |           t          k    rdS t          |           dk    rt          |           dz  }n1d}n.d|cxk    rt          |           k    sn J d            |dk    rdS d|cxk     rd	k     sn J d
            	 t          t          | |                    }n# t          $ r Y dS w xY wt          |          ||z  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)]re   z+unique_share must be in next bounds: (0; 1))lenstart_caching_atsetr   	TypeError)rr   rs   ru   
do_cachingunique_elementss        rP   should_cacher      s*   : J s88'''5s88tc((b.KKKKK++++3s88+++++? ,++ !5|a!NfS+6677   uu
?kL888
s   B. .
B<;B<formatcacheconvert_listliker8   r>   c                   ddl m}  |t                    }|rt          |           s|S t	          | t
          j        t          t          t          f          st          j
        |           } t          |           }t          |          t          |           k     rZ |||          }	  |||d          }n# t          $ r |cY S w xY w|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>   objectr   
isinstancenpndarrayr1   r6   r+   arrayr/   rz   r   r   	is_unique
duplicated)rr   r   r   r   r>   cache_arrayunique_datescache_datess           rP   _maybe_cacher      s   0 &v&&&K KC   	#
NE9MNN 	 (3--Cc{{|s3xx''**<@@K#$f[5QQQ& # # #""""# $. K);+<+G+G+I+I*IJs   (B7 7CCdt_arrayr   utcnameHashable | Noner6   c                    t          j        | j        d          r|rdnd}t          | ||          S t	          | || j                  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   r   )r   is_np_dtyper   r7   r6   )r   r   r   r   s       rP   _box_as_indexliker   
  sT    . x~s++ 9#UUtX"48888HN;;;;rO   r   c                    ddl m}  || |j        j                                      |          }t          |j        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   r   r   Fr   r   )r   r>   r   r   mapr   _values)rr   r   r   r>   results        rP   _convert_and_box_cacher   '  sU    ( VC{06777;;KHHFV^TBBBBrO   raiseuniterrorsr   	yearfirstexactc	                B   t          | t          t          f          rt          j        | d          } n)t          | t
                    rt          j        |           } t          | dd          }	|rdnd}
t          |	t                    rZt          | t          t          f          st          | |
|          S |r(| 
                    d                              d          } | S t          |	t                    r|	j        t          u r|rt          | t                    rct!          t"          | j                  }|	j        j        |                    d          }n|                    d          }t          |d	          } n7|	j        j        |                     d          } n|                     d          } | S t-          j        |	d
          rt1          |	          s:t3          t          j        |           t          j        d          |dk              } t          | t          t          f          st          | |
|          S |r|                     d          S | S |$|t9          d          t;          | ||||          S t          | dd          dk    rt=          d          	 t?          | dtA          j!        |
                    \  } }n]# t<          $ rP |dk    rHt          j"        tG          |           t          j$        dd                    }t          ||          cY S  w xY wtK          |           } |tM          | |          }||dk    rtO          | |||||          S tQ          | ||||d          \  }}|t          j)        |j                  d         }t!          d|          }tU          ||          }|+                    d|j,         d          }t          j-        ||          }t          j-        ||          S t]          |||          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'
    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
    Or   r   Nr   r   UTCFr   r   zM8[s]coerce)	is_coercez#cannot specify both format and unitndimre   zAarg must be a string, datetime, list, tuple, 1-d array, or Series)r   r   r   r\   r   rd   mixedT)r^   r   r   r   allow_objectr   r<   M8[]r   )/r   listtupler   r   r.   getattrr)   r,   r7   
tz_converttz_localizer(   rh   r   r6   r   r0   pyarrow_dtyper   _dt_tz_convert_dt_tz_localizer   r   r   r   asarrayr   
ValueError_to_datetime_with_unitr}   r2   libtimezonesmaybe_get_tzfullrz   
datetime64r!   rp   _array_strptime_with_fallbackr3   datetime_datar4   viewr   _simple_newr   )rr   r   r   r   r   r   r^   r   r   	arg_dtyper   	arg_array_npvaluesr   	tz_parsedout_unitr   dt64_valuesdtas                       rP   _convert_listlike_datetimesr   A  sP   L #e}%% hs#&&&	C,	-	- hsmmWd++I	4B)_-- 1
#}=>> 	8 $7777 	:..&&22599C
	Iz	*	* *
y~/J/J 	1#u%% 1 !4ci@@	*-9 ) 8 8 ? ?II ) 9 9% @ @IIE222(+7((//))%00
	C	(	( 
!),, 	%
3!! H,  C #}=>> 	* $7777 	*??5)))
		BCCC%c4sFCCC	fa	 	 1	$	$O
 
 	
$Su9RSU9V9VWWWQQ   Xws3xxud)C)CDDH 555555	 

C~1#III f//,S$VUFSSS-  FI  #FL11!4
H--Ix00kk"5
"5"5"566'5AAA(48888V48888s   )'K AL+)L+fmtri   c                   t          | ||||          \  }}|t          j        |j                  d         }t	          d|          }t          ||          }	t          j        ||	          }
|r|
                    d          }
t          |
|d	          S |j        t          k    rJ|rHt          j        |j                  d         }t	          d|          }t          |d
| d|d          }|S t          ||j        |d          S )zL
    Call array_strptime, with fallback behavior depending on 'errors'.
    )r   r   r   Nr   r<   )r   r   r   r   F)r   r   r   z, UTC])r   r   r   )r   r   r   r   r   r)   r,   r   r   r6   r   )rr   r   r   r   r   r   r   tz_outr   r   r   ress               rP   r   r     s    $CE&cRRRNFF--a0J%%6555'e<<< 	(..''CSt%0000			C	--a0J%%F"4"4"4"44eLLL
v|$UCCCCrO   c           	     @   t          | d          } t          | t                    r|                     d| d          }d}nVt	          j        |           } | j        j        dv r|                     d| dd          }t          |j                  }	 t          ||d          }nD# t          $ r7 |d	k    r |                     t                    } t          | ||||          cY S w xY wd}n| j        j        d
k    rat	          j        d          5  |                     t          j                  }ddd           n# 1 swxY w Y   t	          j        |           }	|	| |k    z                                  r%t          |||||          }
t"          |
j        |	<   |
S t	          j        d	          5  	 t'          | |          }nh# t          $ r[}|d	k    r<t          |                     t                    ||||          cY d}~cddd           S t          d| d          |d}~ww xY w	 ddd           n# 1 swxY w Y   |                    d          }d}n7|                     t          d          } t+          j        | |||          \  }}t/          ||          }
t          |
t.                    s|
S |
                    d                              |          }
|r2|
j        |
                    d          }
n|
                    d          }
|
S )zF
    to_datetime specalized to the case where a 'unit' is passed.
    T)extract_numpyzdatetime64[r   NiuFr   r   fignore)invalid)r   r   r   r   )overr   z cannot convert input with unit ''zM8[ns])r   r   unit_for_numericsr   r   r   )r5   r   r-   astyper   r   r   kindr   r   r   r   r   errstateint64isnanallr   _datar   r   r   array_to_datetimer7   r   r   r   )rr   r   r   r   r   rm   r   r   
int_valuesmaskr   errs               rP   r   r     s    4
0
0
0C #|$$ 5jj.t...//		joo9>T!! **24222*??C'	22EL)#u5AAA& L L LW$$jj((-c4sFKKKKK	L
 IIY^s""X... 2 2 ZZ11
2 2 2 2 2 2 2 2 2 2 2 2 2 2 28C==Dz)*//11  0T#f   &)T"'*** 
 
	3CdCCCCC*   ((5JJv..dC        
 
 
 
 
 
 
 
 .B4BBB  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 ((8$$CII**V%*00C"4"&	  NC 3T***Ffm,, 
 &&11)<<F
 .9''..FF&&u--FMsl   B) )>C*)C* EE
E7I 9G
I 
H00H+H0I H++H00I  IIc                   |dk    r| }t          d                                          }|dk    rt          d          	 | |z
  } n"# t          $ r}t          d          |d}~ww xY wt           j                                        |z
  }t           j                                        |z
  }t          j        | |k              st          j        | |k               rt          | d          nvt          |           sFt          |           s7t          t          j        |                     st          d|  d	| d
          	 t          j	        |          st          j
        |          rt          ||          }nt          |          }nG# t          $ r}t          d| d          |d}~wt          $ r}t          d| d          |d}~ww xY w|j        t          d| d          |t          d          z
  }	|	t          d|          z  }
t!          |           r;t#          | t$          t&          t          j        f          st          j        |           } | |
z   } | 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)
    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-naivere   )r   to_julian_dater   r}   maxminr   anyr   r$   r"   r'   r   r   r   r   r&   r   r+   r6   r   )rr   originr   originalj0r   j_maxj_minoffset	td_offsetioffsets              rP   _adjust_to_originr   7  s   $ q\\((**3;;CDDD	(CC 	 	 	E 	 ,,..3,,..36#+ 	"&u"5"5 	%BBB  	 __	 (	2B2:c??2S2S	 ;C ; ;& ; ; ;  
	~f%% +f)=)= +"6555"6**" 	T 	T 	T%&I&I&I&IJJPSS 	 	 	E&EEE 	
 9 GfGGGHHHYq\\)	 y6666  	"Zi
5S%T%T 	"*S//CGmJs=    A 
A%A  A%A	F 
GF,,G9GGr   c
                    d S NrN   
rr   r   r^   r   r   r   r   r   r   r   s
             rP   to_datetimer     s	     rO   Series | DictConvertiblec
                    d S r   rN   r   s
             rP   r   r     s	     SrO    list | tuple | Index | ArrayLiker7   c
                    d S r   rN   r   s
             rP   r   r     s	     CrO   r   unix2DatetimeScalarOrArrayConvertible | DictConvertiblebool | lib.NoDefaultr   1DatetimeIndex | Series | DatetimeScalar | NaTTypec
           	        |t           j        ur|dv rt          d          | t          S |dk    rt	          | ||          } t          t          ||||||          }
t          | t                    r9| }|r3| j	        | 
                    d          }n:|                     d          }n#t          | t                    ret          | ||	|
          }|j        s|                     |          }n |
| j        |          }|                     || j        | j                  }nt          | t(          t*          j        f          rt/          | ||          }nut          | t0                    rGt          | ||	|
          }|j        st3          | || j                  }n. |
| || j                  }nt5          |           r	 t7          t8          t:          t<          t>          t@          j!        d	t0          f         |           }t          |||	|
          }n/# tD          $ r" |d
k    r ddl#m$}  |g tJ                    }Y nw xY w|j        st3          ||          }np |
||          }nc |
tA          j&        | g          |          d         }t          | tN                    r)t          |t@          j(                  rtO          |          }|S )aE5  
    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 : {'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`.
    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`.

        .. 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.
    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``, or when parsing datetimes
        with mixed time zones unless ``utc=True``. If parsing datetimes with mixed
        time zones, please specify ``utc=True``.

    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[us]

    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[s]', 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("invalid for Ymd", 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[us]', 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[us, 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 raise a ValueError unless
      ``utc=True``:

    >>> pd.to_datetime(
    ...     ["2020-10-25 02:00 +0200", "2020-10-25 04:00 +0100"]
    ... )  # doctest: +SKIP
    ValueError: Mixed timezones detected. Pass utc=True in to_datetime
    or tz='UTC' in DatetimeIndex to convert to a common timezone.

    - To create a :class:`Series` with mixed offsets and ``object`` dtype, please use
      :meth:`Series.apply` and :func:`datetime.datetime.strptime`:

    >>> import datetime as dt
    >>> ser = pd.Series(["2020-10-25 02:00 +0200", "2020-10-25 04:00 +0100"])
    >>> ser.apply(lambda x: dt.datetime.strptime(x, "%Y-%m-%d %H:%M %z"))
    0    2020-10-25 02:00:00+02:00
    1    2020-10-25 04:00:00+01:00
    dtype: object

    - A mix of timezone-aware and timezone-naive inputs will also raise a ValueError
      unless ``utc=True``:

    >>> from datetime import datetime
    >>> pd.to_datetime(
    ...     ["2020-01-01 01:00:00-01:00", datetime(2020, 1, 1, 3, 0)]
    ... )  # doctest: +SKIP
    ValueError: Mixed timezones detected. Pass utc=True in to_datetime
    or tz='UTC' in DatetimeIndex to convert to a common timezone.

    |

    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[us, 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[us, 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[us, UTC]', freq=None)
    >   r   ISO8601z8Cannot use 'exact' when 'format' is 'mixed' or 'ISO8601'Nr  )r   r   r^   r   r   r   r   )r   r   r   r>   r   r   r   r   ))r   
no_defaultr   r   r   r   r   r   r   r   r   r   r+   r   emptyr   r   _constructorr   r   r*   r   MutableMapping_assemble_from_unit_mappingsr6   r   r&   r   r   r   r   r1   r   r   r   r   r>   r   r   rw   bool_)rr   r   r^   r   r   r   r   r   r   r   r   r   r   valuesargcr>   s                   rP   r   r     s   D
 CN""v1E'E'ESTTT
{
VT22#   #y!! 0" 	0v!..//	C	#	# )""37GHH  	NWW[))FF%%ck6::F%%fCICH%MMFF	C,(:;	<	< ""-c63??	C		  ""37GHH  	B+C38LLLFF%%c6AAAFF	c		 "	3
 dE>2:xNOQT D 'tVU<LMMKK" 	3 	3 	3   %%%%%% &6222KKK	3   	4+D+>>FF%%dF33FF!!"(C5//6::1=c4   	"Z%A%A 	"&\\F
 Ms   AH )IIrF   yearsrG   monthsrH   daysrT   hrU   rV   mrW   rX   srY   rZ   millisecondmillisecondsr[   microsecondr\   )microsecondsr\   
nanosecondnanosecondsc                
   ddl m}mm}  ||           } | j        j        st          d          d fd|                                 D             }d |                                D             }g d}t          |          t          |                                          z
  }t          |          r5d                    t          |                    }	t          d	|	 d
          t          |                                          t          t                                                    z
  }
t          |
          r5d                    t          |
                    }t          d| d          fd} || |d                            dz   || |d                            dz  z    || |d                            z   }	 t          |d|          }n,# t           t          f$ r}t          d|           |d}~ww xY wg d}|D ]n}|                    |          }|U|| v rQ	 | | || |                   |          z  }?# t           t          f$ r}t          d| d|           |d}~ww xY wo|S )a  
    assemble the unit specified fields from the arg (DataFrame)
    Return a Series for actual parsing

    Parameters
    ----------
    arg : DataFrame
    errors : {'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`
    utc : bool
        Whether to convert/localize timestamps to UTC.

    Returns
    -------
    Series
    r   )r=   
to_numericto_timedeltaz#cannot assemble with duplicate keysc                    | t           v rt           |          S |                                 t           v rt           |                                          S | S r   )	_unit_maplower)values    rP   r   z'_assemble_from_unit_mappings.<locals>.fv  sE    IU## ;;==I%%U[[]]++rO   c                (    i | ]}| |          S rN   rN   ).0kr   s     rP   
<dictcomp>z0_assemble_from_unit_mappings.<locals>.<dictcomp>  s#    (((Aqqtt(((rO   c                    i | ]\  }}||	S rN   rN   )r&  r'  vs      rP   r(  z0_assemble_from_unit_mappings.<locals>.<dictcomp>  s    ...A1...rO   )rF   rG   rH   ,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                     |           } t          | j                  r|                     d          } t          | j                  r|                     d          } | S )N)r   float64r   )r#   r   r   r%   )r  r   r  s    rP   r   z,_assemble_from_unit_mappings.<locals>.coerce  sf    F6222 &,'' 	.]]9--F FL)) 	,]]7++FrO   rF   i'  rG   d   rH   z%Y%m%d)r   r   r   zcannot assemble the datetimes: N)r  r  r  rZ   r[   r\   )r   r   zcannot assemble the datetimes [z]: )r   r=   r  r   columnsr   r   keysitemsr|   rz   joinsortedr"  r  r   r}   get)rr   r   r   r=   r   r   unit_revrequiredreq	_requiredexcess_excessr   r  r   unitsur$  r   r  s    `                @@rP   r  r  V  s>   *          )C..C;  @>???   )(((SXXZZ(((D.....H (''H
h--#hmmoo..
.C
3xx 
HHVC[[))	I1:I I I
 
 	
 !!C	(8(8(:(:$;$;;F
6{{ 
((6&>>**RRRR
 
 	
      	s8F#$%%-
&Xg&'
(
(3
.	/
&Xe_%
&
&	' 
KVHVMMMz" K K K@3@@AAsJK  A@@E  Q#,,vvc%j'9'9&QQQQz*    EeEEEE  Ms0   G" "H3HH2 II?$I::I?)r   r   r   )F)r^   r_   r`   ra   )rq   N)rr   r?   rs   rt   ru   rv   r`   rw   )
rr   r?   r   ra   r   rw   r   r8   r`   r>   )FN)r   r   r   rw   r   r   r`   r6   r   )rr   rB   r   r>   r   r   r`   r6   )NFNr   NNT)r   ra   r   r   r   rw   r   ra   r   r   r^   r_   r   r_   r   rw   )
r   rw   r   ri   r   rw   r   ri   r`   r6   )r   rw   r   ri   r`   r6   )	.........)rr   rA   r   r   r^   rw   r   rw   r   rw   r   ra   r   rw   r   ra   r   rw   r`   r   )rr   r   r   r   r^   rw   r   rw   r   rw   r   ra   r   rw   r   ra   r   rw   r`   r>   )rr   r  r   r   r^   rw   r   rw   r   rw   r   ra   r   rw   r   ra   r   rw   r`   r7   )rr   r  r   r   r^   rw   r   rw   r   rw   r   ra   r   r  r   ra   r   ri   r   rw   r`   r  )r   r   r   rw   r`   r>   )z
__future__r   collectionsr   datetimer   	functoolsr   	itertoolsr   typingr   r	   r
   r   r   r   rj   numpyr   pandas._libsr   r   pandas._libs.tslibsr   r   r   r   r   r   r   r   r   pandas._libs.tslibs.conversionr   pandas._libs.tslibs.parsingr   r   pandas._libs.tslibs.strptimer   pandas._typingr   r   r   pandas.util._decoratorsr   pandas.util._exceptionsr    pandas.core.dtypes.commonr!   r"   r#   r$   r%   r&   r'   pandas.core.dtypes.dtypesr(   r)   pandas.core.dtypes.genericr*   r+   pandas.arraysr,   r-   r.   pandas.core.algorithmsr/   pandas.core.arraysr0   pandas.core.arrays.baser1   pandas.core.arrays.datetimesr2   r3   r4   pandas.core.constructionr5   pandas.core.indexes.baser6   pandas.core.indexes.datetimesr7   collections.abcr8   r9   pandas._libs.tslibs.nattyper:   pandas._libs.tslibs.timedeltasr;   r<   r   r=   r>   r   r   r?   rM   rt   ri   r@   r   rA   rB   rC   rE   rS   DictConvertibler{   rp   r   r   r   r   r   r   r   r   r   r
  r"  r  __all__rN   rO   rP   <module>r\     sW   " " " " " " "                                                   	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 E D D D D D        8 7 7 7 7 7         
 / . . . . . 4 4 4 4 4 4                               
         
 * ) ) ) ) ) 2 2 2 2 2 2 2 2 2 2 2 2         
 3 2 2 2 2 2 * * * * * * 7 7 7 7 7 7        
 433333::::::''''''        #Ul\9  9 9 9 9CK    "TMBM9 9 9 9 9.<?O.O   O O O O!&\E&#+,>>M M M M M    y    	 	 	 	 	'u 	 	 	 	 (+56     0 QU9 9 9 9 9x/ / / /f EI< < < < <@ !C C C C C: !#* !G9 G9 G9 G9 G9TD D D D8M M M M`H H HV 
 $'    
 
 $'    
 
 $'    
 H $+"%.I I I I IZ
FV W g	
 
5 E C S c s c s 	$ 4 D  	$!" 4#$ 
+  	2` ` ` `F  rO   