U
    f/e                     @  s  d dl mZ d dlmZmZ d dlZd dl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mZ d dl m!Z!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,m-Z. d dl/m0Z0m1Z1m2Z2 d dl3m4Z4m5Z5m6Z6 d dl7m8Z8 d dl9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZI d dlJmKZKmLZL d dlMmNZNmOZO d dlPmQZQmRZR d dlSmTZTmUZUmVZV d dlWmXZX d dlYmZZZm[Z[ d dl\m]  m^Z_ d dl`maZbmcZc d dldmeZemfZf d dlgmhZh d dlimjZjmkZk d dllmmZm er@d dlmnZn d dlompZpmqZq ee'ef Zre
dddZsG dd  d etZuG d!d deXeZZvG d"d# d#evZwd$Zxd%Zyd&Zzd'Z{e
d(d)dZ|G d*d) d)evZ}d+d, Z~d-d. Zd/d0 Zd1d2 ZdS )3    )annotations)datetime	timedeltaN)TYPE_CHECKINGAnyCallableSequenceTypeVarUnioncastoverload)algoslib)
BaseOffsetIncompatibleFrequencyNaTNaTTypePeriod
ResolutionTick	Timestampdelta_to_nanosecondsiNaT	to_offset)RoundToround_nsint64)integer_op_not_supported)	ArrayLikeDatetimeLikeScalarDtypeDtypeObjNpDtypePositionalIndexer2D)function)AbstractMethodErrorNullFrequencyErrorPerformanceWarning)AppenderSubstitutioncache_readonly)find_stack_level)is_categorical_dtypeis_datetime64_any_dtypeis_datetime64_dtypeis_datetime64tz_dtypeis_datetime_or_timedelta_dtypeis_dtype_equalis_extension_array_dtypeis_float_dtypeis_integer_dtypeis_list_likeis_object_dtypeis_period_dtypeis_string_dtypeis_timedelta64_dtypeis_unsigned_integer_dtypepandas_dtype)DatetimeTZDtypePeriodDtype)is_valid_na_for_dtypeisna)nanopsops)checked_add_with_arrisinunique1d)OpsMixin)NDArrayBackedExtensionArrayravel_compat)arrayextract_array)check_array_indexercheck_setitem_lengths)unpack_zerodim_and_defer)invalid_comparisonmake_invalid_op)frequencies)Literal)DatetimeArrayTimedeltaArrayDatetimeLikeArrayTDatetimeLikeArrayMixin)boundc                   @  s   e Zd ZdZdS )InvalidComparisonzm
    Raised by _validate_comparison_value to indicate to caller it should
    return invalid_comparison.
    N)__name__
__module____qualname____doc__ rZ   rZ   C/tmp/pip-unpacked-wheel-tiezk1ph/pandas/core/arrays/datetimelike.pyrU      s   rU   c                      s"  e Zd ZU dZded< ded< ded< ded	< ed
dddZdddddZeddddZ	dddddZ
ddd
ddddZddd
d d!d"d#Zeddd$d%Zd&d' Zddd(d)Zd*d+ Zeddd,d-Zdd/d0Zdd
d1d2d3Zdd4dd5d6d7Zd8d9d: fd;d<Zd=dd>d?Zd@dAd dB fdCdDZdEdF Zdd
dHdIdJZedKdKdLdMdNZedOdPd5dQdNZedRdSd5dTdNZedddVd5dWdNZdddVd5dXdNZeddZd[d\dKd] fd^d_ZdKdKdL fd`daZdbdc ZedZdKdKdddedfZ dgdh Z!didj Z"ddGdGdkd
d
d
dkdldmZ#dd
ddndodpZ$dd
dqdrdsZ%dtdu Z&dvdw Z'dd
dxdydzd{Z(e)d|d} Z*ddd~dZ+ddddZ,eddddZ-ed
dddZ.e/dfdddddZ0edd Z1e1j2dd Z1eddddZ3eddddZ4eddddZ5eddddZ6edd Z7edZdKdddZ8ed
dddZ9ed
dddZ:ed
dddZ;dd Z<e=dZ>e=dZ?e=dZ@e=dZAe=dZBe=dZCe=dZDe=dZEe=dZFe=dZGe=dZHe=dZIdd ZJeJZKdd ZLeLZMdd ZNddddZOdd ZPdd ZQdd ZRdd ZSdd ZTddĄ ZUddddƄZVdd\dǜddɄZWeXdʃdd̄ ZYdd΄ ZZeXdσddф Z[ddӄ Z\ddՄ Z]ddׄ Z^ddGd؜dd
d؜ddۄZ_ddGd؜dd
d؜dd݄Z`dGdYdޜd
ddޜddZaddGd؜dd
d؜ddZb  ZcS )rS   z
    Shared Base/Mixin class for DatetimeArray, TimedeltaArray, PeriodArray

    Assumes that __new__/__init__ defines:
        _data
        _freq

    and that the inheriting class has methods:
        _generate_range
    ztuple[str, ...]_infer_matcheszCallable[[DtypeObj], bool]_is_recognized_dtypeztuple[type, ...]_recognized_scalars
np.ndarray_ndarrayboolreturnc                 C  s   dS )NTrZ   selfrZ   rZ   r[   _can_hold_na   s    z#DatetimeLikeArrayMixin._can_hold_naNFzDtype | Nonedtypec                 C  s   t | d S Nr$   )re   datarh   freqcopyrZ   rZ   r[   __init__   s    zDatetimeLikeArrayMixin.__init__ztype[DatetimeLikeScalar]c                 C  s   t | dS )z
        The scalar associated with this datelike

        * PeriodArray : Period
        * DatetimeArray : Timestamp
        * TimedeltaArray : Timedelta
        Nrj   rd   rZ   rZ   r[   _scalar_type   s    	z#DatetimeLikeArrayMixin._scalar_typestrDTScalarOrNaT)valuerc   c                 C  s   t | dS )ay  
        Construct a scalar type from a string.

        Parameters
        ----------
        value : str

        Returns
        -------
        Period, Timestamp, or Timedelta, or NaT
            Whatever the type of ``self._scalar_type`` is.

        Notes
        -----
        This should call ``self._check_compatible_with`` before
        unboxing the result.
        Nrj   re   rr   rZ   rZ   r[   _scalar_from_string   s    z*DatetimeLikeArrayMixin._scalar_from_stringz)np.int64 | np.datetime64 | np.timedelta64)rr   setitemrc   c                 C  s   t | dS )a  
        Unbox the integer value of a scalar `value`.

        Parameters
        ----------
        value : Period, Timestamp, Timedelta, or NaT
            Depending on subclass.
        setitem : bool, default False
            Whether to check compatibility with setitem strictness.

        Returns
        -------
        int

        Examples
        --------
        >>> self._unbox_scalar(Timedelta("10s"))  # doctest: +SKIP
        10000000000
        Nrj   )re   rr   ru   rZ   rZ   r[   _unbox_scalar   s    z$DatetimeLikeArrayMixin._unbox_scalarNone)otherru   rc   c                 C  s   t | dS )a  
        Verify that `self` and `other` are compatible.

        * DatetimeArray verifies that the timezones (if any) match
        * PeriodArray verifies that the freq matches
        * Timedelta has no verification

        In each case, NaT is considered compatible.

        Parameters
        ----------
        other
        setitem : bool, default False
            For __setitem__ we may have stricter compatibility restrictions than
            for comparisons.

        Raises
        ------
        Exception
        Nrj   re   rx   ru   rZ   rZ   r[   _check_compatible_with   s    z-DatetimeLikeArrayMixin._check_compatible_withc                 C  s   | j S ri   )r`   rd   rZ   rZ   r[   _data   s    zDatetimeLikeArrayMixin._datac                 C  s   t | dS )zI
        box function to get object from internal representation
        Nrj   )re   xrZ   rZ   r[   	_box_func  s    z DatetimeLikeArrayMixin._box_funcc                 C  s   t j|| jddS )z1
        apply box func to passed values
        F)convert)r   Z	map_inferr}   )re   valuesrZ   rZ   r[   _box_values  s    z"DatetimeLikeArrayMixin._box_valuesc                   s<    j dkr$ fddtt D S  fdd jD S d S )N   c                 3  s   | ]} | V  qd S ri   rZ   ).0nrd   rZ   r[   	<genexpr>  s     z2DatetimeLikeArrayMixin.__iter__.<locals>.<genexpr>c                 3  s   | ]}  |V  qd S ri   )r}   )r   vrd   rZ   r[   r     s     )ndimrangelenasi8rd   rZ   rd   r[   __iter__  s    
zDatetimeLikeArrayMixin.__iter__c                 C  s   | j dS )z
        Integer representation of the values.

        Returns
        -------
        ndarray
            An ndarray with int64 dtype.
        i8)r`   viewrd   rZ   rZ   r[   r     s    zDatetimeLikeArrayMixin.asi8r   c                 C  s   t | dS )z|
        Helper method for astype when converting to strings.

        Returns
        -------
        ndarray[str]
        Nrj   )re   na_repdate_formatrZ   rZ   r[   _format_native_types$  s    z+DatetimeLikeArrayMixin._format_native_types)boxedc                 C  s   dj S )Nz'{}')format)re   r   rZ   rZ   r[   
_formatter.  s    z!DatetimeLikeArrayMixin._formatterzNpDtype | None)rh   rc   c                 C  s    t |rtjt| tdS | jS Nrg   )r5   nprG   listobjectr`   re   rh   rZ   rZ   r[   	__array__5  s    z DatetimeLikeArrayMixin.__array__r"   z&DatetimeLikeArrayMixin | DTScalarOrNaT)keyrc   c                   s*   t  |}t|r|S | ||_|S )z
        This getitem defers to the underlying array, which by-definition can
        only handle list-likes, slices, and integer scalars
        )super__getitem__r   	is_scalar_get_getitem_freq_freq)re   r   result	__class__rZ   r[   r   ;  s
    
z"DatetimeLikeArrayMixin.__getitem__zBaseOffset | Nonec                 C  s   t | j}|r| j}n| jdkr&d}nt| |}d}t|trh| jdk	r`|jdk	r`|j| j }q| j}n@|tkrx| j}n0t	
|rt|tj}t|tr| |S |S )z\
        Find the `freq` attribute to assign to the result of a __getitem__ lookup.
        r   N)r6   rh   rl   r   rI   
isinstanceslicestepEllipsiscomZis_bool_indexerr   Zmaybe_booleans_to_slicer   r   Zuint8r   )re   r   Z	is_periodrl   Znew_keyrZ   rZ   r[   r   I  s$    






z(DatetimeLikeArrayMixin._get_getitem_freqz,int | Sequence[int] | Sequence[bool] | slicezNaTType | Any | Sequence[Any])r   rr   rc   c                   s.   t ||| }|rd S t || |   d S ri   )rJ   r   __setitem___maybe_clear_freq)re   r   rr   Zno_opr   rZ   r[   r   g  s
    
z"DatetimeLikeArrayMixin.__setitem__c                 C  s   d S ri   rZ   rd   rZ   rZ   r[   r   x  s    z(DatetimeLikeArrayMixin._maybe_clear_freqT)rm   c                 C  s  t |}t|r(| | j | jS t|rbt|sbt	|rX|
 }|j| ||dS |  S nt|rt }tjd| j dt|d | j}t|r|d}|r| }|S t|rt| j|rt|rdt| j d| }t|n,t|r|
 }|| |dS tj| |dS d S )	N)rh   rm   zcasting zl values to int64 with .astype(...) is deprecated and will raise in a future version. Use .view(...) instead.
stacklevelZuint64zCannot cast z
 to dtype rg   )r:   r5   r   r   ravelreshapeshaper7   r+   r1   construct_array_type_from_sequencer   r3   r*   warningswarnrh   FutureWarningr9   r   rm   r/   r0   r2   typerV   	TypeErrorr   asarray)re   rh   rm   Zarr_clslevelr   msgrZ   rZ   r[   astype}  sB    




zDatetimeLikeArrayMixin.astyperR   )re   rc   c                 C  s   d S ri   rZ   rd   rZ   rZ   r[   r     s    zDatetimeLikeArrayMixin.viewzLiteral['M8[ns]']rP   c                 C  s   d S ri   rZ   r   rZ   rZ   r[   r     s    zLiteral['m8[ns]']rQ   c                 C  s   d S ri   rZ   r   rZ   rZ   r[   r     s    .r   c                 C  s   d S ri   rZ   r   rZ   rZ   r[   r     s    c                 C  s   |d ks|| j kr&t| | j| j dS t|tr<| j|S t|}t|ttfrh| }|| j	|dS |dkrddl
m} || j	|dS |dkrddl
m} || j	|dS | jj|dS )Nrg   M8[ns]r   rP   zm8[ns]rQ   )rh   r   r`   r   r   r:   r<   r;   r   r   pandas.core.arraysrP   rQ   )re   rh   clsrP   rQ   rZ   rZ   r[   r     s    
r   ztype[DatetimeLikeArrayT]zSequence[DatetimeLikeArrayT]int)r   	to_concataxisrc   c                   s   t  ||}|d   j}d }t|r0 j}nl|dkrdd |D } jd k	rt fdd|D rt|d d |dd  }t fdd|D r j}||_|S )	Nr   c                 S  s   g | ]}t |r|qS rZ   )r   r   r|   rZ   rZ   r[   
<listcomp>  s      z<DatetimeLikeArrayMixin._concat_same_type.<locals>.<listcomp>c                 3  s   | ]}|j  j kV  qd S ri   rl   r   objrZ   r[   r     s     z;DatetimeLikeArrayMixin._concat_same_type.<locals>.<genexpr>r   c                 3  s,   | ]$}|d  d  j  |d d  kV  qdS )r   r   r   Nr   )r   pairr   rZ   r[   r     s     )r   _concat_same_typerh   r6   rl   allzipr   )r   r   r   new_objrh   new_freqpairsr   r   r[   r     s     z(DatetimeLikeArrayMixin._concat_same_typec                   s   t   }| j|_|S ri   )r   rm   rl   r   )re   r   r   rZ   r[   rm     s    
zDatetimeLikeArrayMixin.copyc                 C  s   | j ttfS ri   )r`   r   int64r   rd   rZ   rZ   r[   _values_for_factorize  s    z,DatetimeLikeArrayMixin._values_for_factorize)r   originalrc   c                 C  s   | ||j dS r   rg   )r   r   r   rZ   rZ   r[   _from_factorized  s    z'DatetimeLikeArrayMixin._from_factorizedc              
   C  s.  t |tr:z| |}W n  ttfk
r8   t|Y nX t || jsN|tkr| |}z| 	| W n0 t
tfk
r } zt||W 5 d }~X Y nX nt|st|n~t|t| krtdndz| j|dd}| 	| W nF t
tfk
r( } z"tt|dd rn
t||W 5 d }~X Y nX |S )NzLengths must matchTallow_objectrh   )r   rp   rt   
ValueErrorr   rU   r^   r   ro   rz   r   r4   r   _validate_listliker5   getattr)re   rx   errrZ   rZ   r[   _validate_comparison_value  s.    



z1DatetimeLikeArrayMixin._validate_comparison_valuec                 C  s   t || jrt}ntt|| jr*| |}n\| jtkrPt|rPtj	|| j
d}n
| |}tjdt| d| jj dtt d |}| j|ddS )Nr   zPassing zA to shift is deprecated and will raise in a future version, pass z	 instead.r   Tru   )r=   rh   r   r   r^   ro   r   r   
is_integerZ_from_ordinalrl   r   r   r   rV   r   r*   _unbox)re   
fill_valueZnew_fillrZ   rZ   r[   _validate_shift_value4  s    
	z,DatetimeLikeArrayMixin._validate_shift_value)allow_listlikeru   unboxc             
   C  s   t |trTz| |}W q tk
rP } z| ||}t||W 5 d}~X Y qX n\t|| jrft}nJt	|r| ||}t|n,t || j
r| |}n| ||}t||s|S | j||dS )av  
        Validate that the input value can be cast to our scalar_type.

        Parameters
        ----------
        value : object
        allow_listlike: bool, default False
            When raising an exception, whether the message should say
            listlike inputs are allowed.
        setitem : bool, default True
            Whether to check compatibility with setitem strictness.
        unbox : bool, default True
            Whether to unbox the result before returning.  Note: unbox=False
            skips the setitem compatibility check.

        Returns
        -------
        self._scalar_type or NaT
        Nr   )r   rp   rt   r   _validation_error_messager   r=   rh   r   r>   r^   ro   rv   )re   rr   r   ru   r   r   r   rZ   rZ   r[   _validate_scalarS  s$    

z'DatetimeLikeArrayMixin._validate_scalar)r   rc   c                 C  sB   |r"d| j j dt|j d}nd| j j dt|j d}|S )a+  
        Construct an exception message on validation error.

        Some methods allow only scalar inputs, while others allow either scalar
        or listlike.

        Parameters
        ----------
        allow_listlike: bool, default False

        Returns
        -------
        str
        zvalue should be a 'z"', 'NaT', or array of those. Got 'z
' instead.z' or 'NaT'. Got ')ro   rV   r   )re   rr   r   r   rZ   rZ   r[   r     s    z0DatetimeLikeArrayMixin._validation_error_messager   c              	   C  sj  t |t| r|S t |tr<t|dkr<t| jg | jdS t|dr|jtkrt	|| j
krzt| |}W n8 ttfk
r   |r| Y S | |d}t|Y nX t|}t|dd}t|jdrzt| j|| jd}W n tk
r   Y nX t|jr,t|jj| jr,| }t|dd}|r@t|jr@n&t| |jsf| |d}t||S )Nr   rg   rh   TZextract_numpystring)r   r   r   r   r   rh   hasattrr   r   infer_dtyper\   r   r   r   pd_arrayrH   r0   r+   
categoriesZ_internal_get_valuesr5   r]   )re   rr   r   r   rZ   rZ   r[   r     s<    z)DatetimeLikeArrayMixin._validate_listlikec                 C  s,   t |s| j|dddS | |}| |S )NTF)r   ru   )r4   r   r   r   rs   rZ   rZ   r[   _validate_searchsorted_value  s    
z3DatetimeLikeArrayMixin._validate_searchsorted_valuec                 C  s0   t |r| |}n| j|ddS | j|ddS )NT)r   r   )r4   r   r   r   rs   rZ   rZ   r[   _validate_setitem_value  s    z.DatetimeLikeArrayMixin._validate_setitem_valuez6np.int64 | np.datetime64 | np.timedelta64 | np.ndarray)ru   rc   c                 C  s2   t |r| j||d}n| j||d |j}|S )zZ
        Unbox either a scalar with _unbox_scalar or an instance of our own type.
        r   )r   r   rv   rz   r`   ry   rZ   rZ   r[   r     s
    
zDatetimeLikeArrayMixin._unboxc                 C  s   ddl m} || |jS )Nr   )Index)Zpandasr   maprG   )re   Zmapperr   rZ   rZ   r[   r     s    zDatetimeLikeArrayMixin.mapc              	   C  s   t |dst|}|jjdkr0tj| jtdS t|t	| sdddddd	g}|jt
krtj|d
d}||kr|dkrxn(d|krt| t
|S tj| jtdS zt	| |}W n$ tk
r   t| t
| Y S X z| | W n* ttfk
r   tj| jtd Y S X t| j|jS )z
        Compute boolean array of whether each value is found in the
        passed set of values.

        Parameters
        ----------
        values : set or sequence of values

        Returns
        -------
        ndarray[bool]
        rh   )fiucrg   r   timedelta64r   
datetime64dateZperiodF)skipnar   mixed)r   r   r   rh   kindzerosr   ra   r   r   r   r   r   rB   r   r   r   rz   r   r   )re   r   Z	inferableinferredrZ   rZ   r[   rB   	  s:    


zDatetimeLikeArrayMixin.isinc                 C  s   | j S ri   )_isnanrd   rZ   rZ   r[   r>   A  s    zDatetimeLikeArrayMixin.isnac                 C  s
   | j tkS )z-
        return if each value is nan
        )r   r   rd   rZ   rZ   r[   r   D  s    zDatetimeLikeArrayMixin._isnanc                 C  s   t | j S )zJ
        return if I have any nans; enables various perf speedups
        )ra   r   anyrd   rZ   rZ   r[   _hasnansK  s    zDatetimeLikeArrayMixin._hasnans)r   rc   c                 C  s6   | j r2|r||}|dkr"tj}t|| j| |S )az  
        Parameters
        ----------
        result : np.ndarray
        fill_value : object, default iNaT
        convert : str, dtype or None

        Returns
        -------
        result : ndarray with values replace by the fill_value

        mask the result if needed, convert to the provided dtype if its not
        None

        This is an internal routine.
        N)r   r   r   nanputmaskr   )re   r   r   r~   rZ   rZ   r[   _maybe_mask_resultsR  s    
z*DatetimeLikeArrayMixin._maybe_mask_resultsc                 C  s   | j S )zK
        Return the frequency object if it is set, otherwise None.
        r   rd   rZ   rZ   r[   rl   p  s    zDatetimeLikeArrayMixin.freqc                 C  s8   |d k	r.t |}| | | | jdkr.td|| _d S )Nr   zCannot set freq with ndim > 1)r   _validate_frequencyr   r   r   rs   rZ   rZ   r[   rl   w  s    
z
str | Nonec                 C  s   | j dkrdS | j jS )zU
        Return the frequency object as a string if its set, otherwise None.
        N)rl   freqstrrd   rZ   rZ   r[   r     s    
zDatetimeLikeArrayMixin.freqstrc                 C  s6   | j dkrdS zt| W S  tk
r0   Y dS X dS )z
        Tries to return a string representing a frequency guess,
        generated by infer_freq.  Returns None if it can't autodetect the
        frequency.
        r   N)r   rN   Z
infer_freqr   rd   rZ   rZ   r[   inferred_freq  s    
z$DatetimeLikeArrayMixin.inferred_freqzResolution | Nonec                 C  s:   | j }|d krd S zt|W S  tk
r4   Y d S X d S ri   )r   r   Zget_reso_from_freqKeyError)re   r   rZ   rZ   r[   _resolution_obj  s    z&DatetimeLikeArrayMixin._resolution_objc                 C  s   | j jS )zO
        Returns day, hour, minute, second, millisecond or microsecond
        )r  attrnamerd   rZ   rZ   r[   
resolution  s    z!DatetimeLikeArrayMixin.resolutionc              
   K  s   |j }|jdks||jkrdS z:| jf |d dt||d|}t|j|jsVtW nJ tk
r } z,dt	|krz|td| d|j |W 5 d}~X Y nX dS )am  
        Validate that a frequency is compatible with the values of a given
        Datetime Array/Index or Timedelta Array/Index

        Parameters
        ----------
        index : DatetimeIndex or TimedeltaIndex
            The index on which to determine if the given frequency is valid
        freq : DateOffset
            The frequency to validate
        r   Nstartendperiodsrl   z	non-fixedInferred frequency 9 from passed values does not conform to passed frequency )
r  sizer   _generate_ranger   r   Zarray_equalr   r   rp   )r   indexrl   kwargsr   Zon_freqerZ   rZ   r[   r     s,       z*DatetimeLikeArrayMixin._validate_frequency)r   rc   c                 O  s   t | d S ri   rj   )r   r  r  r	  rl   argsr  rZ   rZ   r[   r    s    z&DatetimeLikeArrayMixin._generate_rangec                 C  s   t j| jddd S )NTZtimeliker   r   Zis_monotonicr   rd   rZ   rZ   r[   _is_monotonic_increasing  s    z/DatetimeLikeArrayMixin._is_monotonic_increasingc                 C  s   t j| jddd S )NTr  r   r  rd   rZ   rZ   r[   _is_monotonic_decreasing  s    z/DatetimeLikeArrayMixin._is_monotonic_decreasingc                 C  s   t t| jd| jkS )NK)r   rC   r   r   r  rd   rZ   rZ   r[   
_is_unique  s    z!DatetimeLikeArrayMixin._is_uniquec           	   	   C  s
  | j dkr6t|dd | jkr6||  | | jS z| |}W n  tk
rd   t| || Y S X t|dd }t|rt	j
dd  t|t	| t|}W 5 Q R X |S | |}|| jd|d}t|}| j|B }| r|tjk}t	||| |S )Nr   r   rh   ignore)r   r   )r   r   r   r   r   r   rU   rL   r5   r   Zerrstater@   Zcomp_method_OBJECT_ARRAYr   r   r   r   r`   r   r>   r   r   operatorner   )	re   rx   oprh   r   Z
other_valsZo_maskmaskZ
nat_resultrZ   rZ   r[   _cmp_method  s.      



z"DatetimeLikeArrayMixin._cmp_method__pow____rpow____mul____rmul____truediv____rtruediv____floordiv____rfloordiv____mod____rmod__
__divmod____rdivmod__c                 C  s$   t dt| j dt|j d S )Nzcannot add  and r   r   rV   re   rx   rZ   rZ   r[   _add_datetimelike_scalar  s    z/DatetimeLikeArrayMixin._add_datetimelike_scalarc                 C  s$   |t k	sttdt| j d S )Nz"cannot subtract a datelike from a )r   AssertionErrorr   r   rV   r,  rZ   rZ   r[   _sub_datetimelike_scalar   s    z/DatetimeLikeArrayMixin._sub_datetimelike_scalarc                 C  s   t dt| j d S )Nzcannot subtract Period from a r+  r,  rZ   rZ   r[   _sub_period'  s    z"DatetimeLikeArrayMixin._sub_periodr   )rx   c                 C  s   t dt| j d S )Nzcannot add Period to a r+  r,  rZ   rZ   r[   _add_period+  s    z"DatetimeLikeArrayMixin._add_periodc                 C  s   t | d S ri   rj   )re   offsetrZ   rZ   r[   _add_offset/  s    z"DatetimeLikeArrayMixin._add_offsetc                 C  s   t |r4tj| jdd}|t t| || jdS t|}t	| j
|| jd}|d}| |}|| jj}d}t| jtst| jr| j}t| j|| j|dS )zk
        Add a delta of a timedeltalike

        Returns
        -------
        Same type as self
        r   rg   )arr_maskNrh   rl   )r>   r   emptyr   fillr   r   rh   r   rA   r   r   r   r   r`   r   rl   r   r6   _simple_new)re   rx   
new_valuesincr   rZ   rZ   r[   _add_timedeltalike_scalar2  s"    


  z0DatetimeLikeArrayMixin._add_timedeltalike_scalarc                 C  s   t | t |krtdt|tjr:ddlm} ||}| j}|j}t	||| j
|j
d}| jsf|jr| j
|j
B }t||t t| || jdS )zl
        Add a delta of a TimedeltaIndex

        Returns
        -------
        Same type as self
        z$cannot add indices of unequal lengthr   r   )r4  Zb_maskrg   )r   r   r   r   ndarrayr   rQ   r   r   rA   r   r   r   r   r   rh   )re   rx   rQ   Zself_i8Zother_i8r9  r  rZ   rZ   r[   _add_timedelta_arraylikeP  s"    

   z/DatetimeLikeArrayMixin._add_timedelta_arraylikec                 C  sZ   t | jr*tdt| j dttj tj| jtj	d}|
t t| || jddS )z$
        Add pd.NaT to self
        zCannot add r*  rg   Nr5  )r6   rh   r   r   rV   r   r   r6  r   r   r7  r   re   r   rZ   rZ   r[   _add_natn  s    

zDatetimeLikeArrayMixin._add_natc                 C  s&   t j| jt jd}|t |dS )z+
        Subtract pd.NaT from self
        rg   ztimedelta64[ns])r   r6  r   r   r7  r   r   r>  rZ   rZ   r[   _sub_nat}  s    

zDatetimeLikeArrayMixin._sub_natc                 C  s    t d|j dt| j d S )Ncannot subtract z-dtype from )r   rh   r   rV   r,  rZ   rZ   r[   _sub_period_array  s    z(DatetimeLikeArrayMixin._sub_period_arrayc              	   C  s   |t jt jfkstt|dkr8| jdkr8|| |d S tdt| j	 dt
 | j|jksnt| j|jft * tjdtd || dt|}W 5 Q R X t| }t|dd	| j}|S )
z
        Add or subtract array-like of DateOffset objects

        Parameters
        ----------
        other : np.ndarray[object]
        op : {operator.add, operator.sub}

        Returns
        -------
        result : same class as self
        r   r   z)Adding/subtracting object-dtype array to z not vectorizedr  )categoryOTr   )r  addsubr.  r   r   r   r   r   rV   r&   r   catch_warningsfilterwarningsr   r   r   r   r   r   rH   r   )re   rx   r  Z
res_valuesr   rZ   rZ   r[   _addsub_object_array  s&    
  z+DatetimeLikeArrayMixin._addsub_object_arrayr	  c                 C  s   |dk	r4|| j kr4t|tr$t|}|| }| | S |dksHt| dkrP|  S | j dkrbtd| d || j   }| d || j   }| j||d| j dS )a  
        Shift each value by `periods`.

        Note this is different from ExtensionArray.shift, which
        shifts the *position* of each element, padding the end with
        missing values.

        Parameters
        ----------
        periods : int
            Number of periods to shift by.
        freq : pandas.DateOffset, pandas.Timedelta, or str
            Frequency increment to shift by.
        Nr   zCannot shift with no freqr   r  )rl   r   rp   r   r   rm   r%   r  )re   r	  rl   r2  r  r  rZ   rZ   r[   _time_shift  s    

z"DatetimeLikeArrayMixin._time_shift__add__c                 C  sd  t |dd }|tkr |  }nt|tttjfr>| |}nt|t	rT| 
|}nt|ttjfrp| |}nt|trt| jr| |}nt|rt| jst| | |}nzt|r| |}nft|r| |tj}nNt|st|r | |S t|r.t| jst| |  |tj}nt!S t|tj"r`t|jr`ddl#m$} ||S |S Nrh   r   r   )%r   r   r?  r   r   r   r   r   r;  r   r3  r   r   r-  r   r8   rh   r1  r   r   r6   r   rK  r=  r5   rI  r  rE  r-   r.   _add_datetime_arrayliker3   _addsub_int_arrayNotImplementedr<  r   rQ   re   rx   other_dtyper   rQ   rZ   rZ   r[   rL    s<    




zDatetimeLikeArrayMixin.__add__c                 C  s
   |  |S ri   )rL  r,  rZ   rZ   r[   __radd__  s    zDatetimeLikeArrayMixin.__radd____sub__c                 C  s|  t |dd }|tkr |  }n*t|tttjfrB| | }nt|t	rZ| 
| }nt|ttjfrv| |}nt|rt| jst| | | }nt|tr| |}nt|r| | }n~t|r| |tj}nft|st|r| |}nHt|r| |}n2t |rFt| js6t| | !|tj}nt"S t|tj#rxt|jrxddl$m%} ||S |S rM  )&r   r   r@  r   r   r   r   r   r;  r   r3  r   r   r/  r   r   r6   rh   r   rK  r   r0  r8   r=  r5   rI  r  rF  r-   r.   _sub_datetime_arraylikerB  r3   rO  rP  r<  r   rQ   rQ  rZ   rZ   r[   rT    s@    





zDatetimeLikeArrayMixin.__sub__c                 C  s   t |dd }t|rZt| jrZt|r4t||  S t|tsRddl	m
} ||}||  S t| jrt|drt|jstdt| j dt|j nNt| jrt|rtdt| j d|j nt| jrtd| } |  | S | |  S )Nrh   r   r   rA  z from rQ   )r   r,   r8   rh   r   r   r   r   rS   r   rP   r   r   r   rV   r6   r   )re   rx   rR  rP   rZ   rZ   r[   __rsub__J  s.    




zDatetimeLikeArrayMixin.__rsub__c                 C  s2   | | }|d d  | d d < t | js.|j| _| S ri   r6   rh   r   re   rx   r   rZ   rZ   r[   __iadd__m  s
    
zDatetimeLikeArrayMixin.__iadd__c                 C  s2   | | }|d d  | d d < t | js.|j| _| S ri   rW  rX  rZ   rZ   r[   __isub__v  s
    
zDatetimeLikeArrayMixin.__isub__r   r   
int | Nonec                K  s   t d| t || j t| jrxtj| j	d||d}|t
krHt
S |	d}|dksd| jdkrn| |S | |S tj| j||d}| ||S )a  
        Return the minimum value of the Array or minimum along
        an axis.

        See Also
        --------
        numpy.ndarray.min
        Index.min : Return the minimum value in an Index.
        Series.min : Return the minimum value in a Series.
        rZ   r   r[  r   Nr   )nvZvalidate_minvalidate_minmax_axisr   r6   rh   r?   Znanminr`   r   r   r}   _from_backing_data_wrap_reduction_resultre   r   r   r  r   rZ   rZ   r[   min  s     

  


zDatetimeLikeArrayMixin.minc                K  s   t d| t || j t| jrxtj| j	d||d}|t
krH|S |	d}|dksd| jdkrn| |S | |S tj| j||d}| ||S )a  
        Return the maximum value of the Array or maximum along
        an axis.

        See Also
        --------
        numpy.ndarray.max
        Index.max : Return the maximum value in an Index.
        Series.max : Return the maximum value in a Series.
        rZ   r   r[  r   Nr   )r]  Zvalidate_maxr^  r   r6   rh   r?   Znanmaxr`   r   r   r}   r_  r`  ra  rZ   rZ   r[   max  s     

  


zDatetimeLikeArrayMixin.max)r   r   c                C  sD   t | jr tdt| j dtj| j|||  d}| 	||S )an  
        Return the mean value of the Array.

        .. versionadded:: 0.25.0

        Parameters
        ----------
        skipna : bool, default True
            Whether to ignore any NaT elements.
        axis : int, optional, default 0

        Returns
        -------
        scalar
            Timestamp or Timedelta.

        See Also
        --------
        numpy.ndarray.mean : Returns the average of array elements along a given axis.
        Series.mean : Return the mean value in a Series.

        Notes
        -----
        mean is only defined for Datetime and Timedelta dtypes, not for Period.
        zmean is not implemented for zX since the meaning is ambiguous.  An alternative is obj.to_timestamp(how='start').mean()r   r   r  )
r6   rh   r   r   rV   r?   Znanmeanr`   r>   r`  )re   r   r   r   rZ   rZ   r[   mean  s    
   zDatetimeLikeArrayMixin.meanc                K  s   t d| |d k	r*t|| jkr*tdt| jr|tj| j	
d||d}|
d}|d ksh| jdkrr| |S | |S tj| j	||d}| ||S )NrZ   z abs(axis) must be less than ndimr   r[  r   r   )r]  Zvalidate_medianabsr   r   r6   rh   r?   Z	nanmedianr`   r   r}   r_  r`  ra  rZ   rZ   r[   median  s    

  


zDatetimeLikeArrayMixin.median)NNF)F)F)r   N)F)N)T).)N)r   )F)F)F)N)drV   rW   rX   rY   __annotations__r)   rf   rn   propertyro   rt   rv   rz   r{   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   classmethodr   rm   r   r   r   r   r   r   r   r   r   r   rF   r   rB   r>   r   r   r   r   rl   setterr   r  r  r  r   r  r  r  r  r  rM   r  r  r   r!  r"  r#  r$  r%  r&  r'  r(  r)  r-  rN  r/  rU  r0  r1  r3  r;  r=  r?  r@  rB  rI  rK  rK   rL  rS  rT  rV  rY  rZ  rb  rc  re  rg  __classcell__rZ   rZ   r   r[   rS      s  

  

2# 	$#;2	 

8 


	
&#*$
2
3#	'c                   @  s*   e Zd ZdZedddddddZd	S )
DatelikeOpszK
    Common ops for DatetimeIndex/PeriodIndex, but not TimedeltaIndex.
    zNhttps://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior)URLrp   r_   )r   rc   c                 C  s   | j |tjd}|tS )a  
        Convert to Index using specified date_format.

        Return an Index of formatted strings specified by date_format, which
        supports the same string format as the python standard library. Details
        of the string format can be found in `python string format
        doc <%(URL)s>`__.

        Parameters
        ----------
        date_format : str
            Date format string (e.g. "%%Y-%%m-%%d").

        Returns
        -------
        ndarray
            NumPy ndarray of formatted strings.

        See Also
        --------
        to_datetime : Convert the given argument to datetime.
        DatetimeIndex.normalize : Return DatetimeIndex with times to midnight.
        DatetimeIndex.round : Round the DatetimeIndex to the specified freq.
        DatetimeIndex.floor : Floor the DatetimeIndex to the specified freq.

        Examples
        --------
        >>> rng = pd.date_range(pd.Timestamp("2018-03-10 09:00"),
        ...                     periods=3, freq='s')
        >>> rng.strftime('%%B %%d, %%Y, %%r')
        Index(['March 10, 2018, 09:00:00 AM', 'March 10, 2018, 09:00:01 AM',
               'March 10, 2018, 09:00:02 AM'],
              dtype='object')
        )r   r   )r   r   r   r   r   )re   r   r   rZ   rZ   r[   strftime  s    'zDatelikeOps.strftimeN)rV   rW   rX   rY   r(   ro  rZ   rZ   rZ   r[   rm    s
   rm  a*  
    Perform {op} operation on the data to the specified `freq`.

    Parameters
    ----------
    freq : str or Offset
        The frequency level to {op} the index to. Must be a fixed
        frequency like 'S' (second) not 'ME' (month end). See
        :ref:`frequency aliases <timeseries.offset_aliases>` for
        a list of possible `freq` values.
    ambiguous : 'infer', bool-ndarray, 'NaT', default 'raise'
        Only relevant for DatetimeIndex:

        - 'infer' will attempt to infer fall dst-transition hours based on
          order
        - bool-ndarray where True signifies a DST time, False designates
          a non-DST time (note that this flag is only applicable for
          ambiguous times)
        - 'NaT' will return NaT where there are ambiguous times
        - 'raise' will raise an AmbiguousTimeError if there are ambiguous
          times.

    nonexistent : 'shift_forward', 'shift_backward', 'NaT', timedelta, default 'raise'
        A nonexistent time does not exist in a particular timezone
        where clocks moved forward due to DST.

        - 'shift_forward' will shift the nonexistent time forward to the
          closest existing time
        - 'shift_backward' will shift the nonexistent time backward to the
          closest existing time
        - 'NaT' will return NaT where there are nonexistent times
        - timedelta objects will shift nonexistent times by the timedelta
        - 'raise' will raise an NonExistentTimeError if there are
          nonexistent times.

    Returns
    -------
    DatetimeIndex, TimedeltaIndex, or Series
        Index of the same type for a DatetimeIndex or TimedeltaIndex,
        or a Series with the same index for a Series.

    Raises
    ------
    ValueError if the `freq` cannot be converted.

    Examples
    --------
    **DatetimeIndex**

    >>> rng = pd.date_range('1/1/2018 11:59:00', periods=3, freq='min')
    >>> rng
    DatetimeIndex(['2018-01-01 11:59:00', '2018-01-01 12:00:00',
                   '2018-01-01 12:01:00'],
                  dtype='datetime64[ns]', freq='T')
    a\  >>> rng.round('H')
    DatetimeIndex(['2018-01-01 12:00:00', '2018-01-01 12:00:00',
                   '2018-01-01 12:00:00'],
                  dtype='datetime64[ns]', freq=None)

    **Series**

    >>> pd.Series(rng).dt.round("H")
    0   2018-01-01 12:00:00
    1   2018-01-01 12:00:00
    2   2018-01-01 12:00:00
    dtype: datetime64[ns]
    a\  >>> rng.floor('H')
    DatetimeIndex(['2018-01-01 11:00:00', '2018-01-01 12:00:00',
                   '2018-01-01 12:00:00'],
                  dtype='datetime64[ns]', freq=None)

    **Series**

    >>> pd.Series(rng).dt.floor("H")
    0   2018-01-01 11:00:00
    1   2018-01-01 12:00:00
    2   2018-01-01 12:00:00
    dtype: datetime64[ns]
    aZ  >>> rng.ceil('H')
    DatetimeIndex(['2018-01-01 12:00:00', '2018-01-01 12:00:00',
                   '2018-01-01 13:00:00'],
                  dtype='datetime64[ns]', freq=None)

    **Series**

    >>> pd.Series(rng).dt.ceil("H")
    0   2018-01-01 12:00:00
    1   2018-01-01 12:00:00
    2   2018-01-01 13:00:00
    dtype: datetime64[ns]
    TimelikeOpsTTimelikeOpsc                      s   e Zd ZdZdd Zeee jddd#ddZ	eee
 jd	dd$d
dZeee jddd%ddZddddddddZddddddddZddddZdd Zd&dd  fd!d"Z  ZS )'rq  zK
    Common ops for TimedeltaIndex/DatetimeIndex, but not PeriodIndex.
    c           
      C  s   t | jr@td| } | d }|||||}|j| j||dS | d}ttj|}t	|j
}t|||}	| j|	td}|| jj}| j|| jdS )NrP   )	ambiguousnonexistentr   )r   rg   )r.   rh   r   Ztz_localize_roundtzr   r   r<  r   nanosr   r   r   r`   r8  )
re   rl   moderr  rs  Znaiver   r   rv  Z	result_i8rZ   rZ   r[   rt    s     


  

zTimelikeOps._roundround)r  raisec                 C  s   |  |tj||S ri   )rt  r   ZNEAREST_HALF_EVENre   rl   rr  rs  rZ   rZ   r[   rx    s    zTimelikeOps.roundfloorc                 C  s   |  |tj||S ri   )rt  r   ZMINUS_INFTYrz  rZ   rZ   r[   r{    s    zTimelikeOps.floorceilc                 C  s   |  |tj||S ri   )rt  r   Z
PLUS_INFTYrz  rZ   rZ   r[   r|    s    zTimelikeOps.ceilNTr[  r\  ra   c                C  s   t j| j|||  dS Nrd  )r?   Znananyr`   r>   re   r   r   rZ   rZ   r[   r     s    zTimelikeOps.anyc                C  s   t j| j|||  dS r}  )r?   Znanallr`   r>   r~  rZ   rZ   r[   r     s    zTimelikeOps.allrw   rb   c                 C  s
   d | _ d S ri   r   rd   rZ   rZ   r[   r     s    zTimelikeOps._maybe_clear_freqc                 C  sJ   |dkr
n.t | dkr"t|tr"n|dks.tt| j}|  }||_|S )z
        Helper to get a view on the same data, with a new freq.

        Parameters
        ----------
        freq : DateOffset, None, or "infer"

        Returns
        -------
        Same type as self
        Nr   infer)r   r   r   r.  r   r  r   r   )re   rl   ZarrrZ   rZ   r[   
_with_freq  s    
zTimelikeOps._with_freqr   F)sortc                   sh   | j d k	rZtjt| tjd}|  }|rR| j jdk rR|d d d }|d d d }||fS t j|dS )Nrg   r   r   )na_sentinel)	rl   r   Zaranger   Zintprm   r   r   	factorize)re   r  r  codesZuniquesr   rZ   r[   r    s    
zTimelikeOps.factorize)ry  ry  )ry  ry  )ry  ry  )r   F)rV   rW   rX   rY   rt  r'   
_round_doc_round_exampler   rx  _floor_exampler{  _ceil_exampler|  r   r   r   r  r  rl  rZ   rZ   r   r[   rq    s   c                 C  s8   | dk	r4t | rt| } nt | s4td|  | S )a9  
    If a `periods` argument is passed to the Datetime/Timedelta Array/Index
    constructor, cast it to an integer.

    Parameters
    ----------
    periods : None, float, int

    Returns
    -------
    periods : None or int

    Raises
    ------
    TypeError
        if periods is None, float, or int
    Nzperiods must be a number, got )r   Zis_floatr   r   r   rJ  rZ   rZ   r[   validate_periods  s    


r  c                 C  sF   d}d}| dkrd}d}n$| dkr(d}n| dkr6d}nt d||fS )a%  
    Check that the `closed` argument is among [None, "left", "right"]

    Parameters
    ----------
    closed : {None, "left", "right"}

    Returns
    -------
    left_closed : bool
    right_closed : bool

    Raises
    ------
    ValueError : if argument is not among valid values
    FNTleftrightz/Closed has to be either 'left', 'right' or None)r   )closedZleft_closedZright_closedrZ   rZ   r[   validate_endpoints  s    r  c                 C  sH   |dk	r@| dk	r0| |kr0t d| d| j n| dkr<|} d}| |fS )a  
    If the user passes a freq and another freq is inferred from passed data,
    require that they match.

    Parameters
    ----------
    freq : DateOffset or None
    inferred_freq : DateOffset or None
    freq_infer : bool

    Returns
    -------
    freq : DateOffset or None
    freq_infer : bool

    Notes
    -----
    We assume at this point that `maybe_infer_freq` has been called, so
    `freq` is either a DateOffset object or None.
    Nr
  r  F)r   r   )rl   r  
freq_inferrZ   rZ   r[   validate_inferred_freq3  s    r  c                 C  s0   d}t | ts(| dkr t| } nd}d} | |fS )a  
    Comparing a DateOffset to the string "infer" raises, so we need to
    be careful about comparisons.  Make a dummy variable `freq_infer` to
    signify the case where the given freq is "infer" and set freq to None
    to avoid comparison trouble later on.

    Parameters
    ----------
    freq : {DateOffset, None, str}

    Returns
    -------
    freq : {DateOffset, None}
    freq_infer : bool
        Whether we should inherit the freq of passed data.
    Fr  TN)r   r   r   )rl   r  rZ   rZ   r[   maybe_infer_freqV  s    

r  )
__future__r   r   r   r  typingr   r   r   r   r	   r
   r   r   r   Znumpyr   Zpandas._libsr   r   Zpandas._libs.tslibsr   r   r   r   r   r   r   r   r   r   r   Zpandas._libs.tslibs.fieldsr   r   Zpandas._libs.tslibs.timestampsr   Zpandas._typingr   r   r   r    r!   r"   Zpandas.compat.numpyr#   r]  Zpandas.errorsr$   r%   r&   Zpandas.util._decoratorsr'   r(   r)   Zpandas.util._exceptionsr*   Zpandas.core.dtypes.commonr+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   Zpandas.core.dtypes.dtypesr;   r<   Zpandas.core.dtypes.missingr=   r>   Zpandas.corer?   r@   Zpandas.core.algorithmsrA   rB   rC   Zpandas.core.arraylikerD   Zpandas.core.arrays._mixinsrE   rF   Zpandas.core.commoncorecommonr   Zpandas.core.constructionrG   r   rH   Zpandas.core.indexersrI   rJ   Zpandas.core.ops.commonrK   Zpandas.core.ops.invalidrL   rM   Zpandas.tseriesrN   rO   r   rP   rQ   rq   rR   	ExceptionrU   rS   rm  r  r  r  r  rp  rq  r  r  r  r  rZ   rZ   rZ   r[   <module>   sn   (
4 H	          s08i!#