3 6cY@sdZddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z mZmZddlmZdd lmZd d gZGd d d eZGdddeZGdd d eZGdddeZGdddeZeZddd ZGdddeZeZddZddZ dS)a This module offers a generic date/time string parser which is able to parse most known formats to represent a date and/or time. This module attempts to be forgiving with regards to unlikely input formats, returning a datetime object even for dates which are ambiguous. If an element of a date/time stamp is omitted, the following rules are applied: - If AM or PM is left unspecified, a 24-hour clock is assumed, however, an hour on a 12-hour clock (``0 <= hour <= 12``) *must* be specified if AM or PM is specified. - If a time zone is omitted, a timezone-naive datetime is returned. If any other elements are missing, they are taken from the :class:`datetime.datetime` object passed to the parameter ``default``. If this results in a day number exceeding the valid number of days per month, the value falls back to the end of the month. Additional resources about date/time string formats can be found below: - `A summary of the international standard date and time notation `_ - `W3C Date and Time Formats `_ - `Time Formats (Planetary Rings Node) `_ - `CPAN ParseDate module `_ - `Java SimpleDateFormat Class `_ )unicode_literalsN)StringIO) monthrange) text_type binary_type integer_types) relativedelta)tzparse parserinfoc@sneZdZejdZddZddZddZdd Z d d Z e d d Z e ddZ e ddZe ddZdS)_timelexz([.,])cCsdt|tr|j}t|tr$t|}t|dddkrHtdj|jj d||_ g|_ g|_ d|_ dS)Nreadz8Parser must be a string or character stream, not {itype})ZitypeF) isinstancerdecoderrgetattr TypeErrorformat __class____name__instream charstack tokenstackeof)selfrr/usr/lib/python3.6/parser.py__init__4s  z_timelex.__init__cCs|jr|jjdSd}d}d}x|js|jr>|jjd}n&|jjd}x|dkrb|jjd}qLW|srd|_Pq"|s|}|j|rd}n$|j|rd}n|j|rd }PnPq"|dkrd}|j|r||7}n$|d kr||7}d }n|jj |Pq"|dkrX|j|r||7}n>|d ks:|d krHt |d krH||7}d}n|jj |Pq"|d krd}|d ks||j|r||7}n6|j|r|dd kr||7}d}n|jj |Pq"|dkr"|d ks|j|r||7}q"|j|r|dd kr||7}d }q"|jj |Pq"W|dkr|sN|j d dksN|ddkr|j j |}|d}x(|ddD]}|rp|jj |qpW|dkr|j d dkr|jd d }|S)a This function breaks the time string into lexical units (tokens), which can be parsed by the parser. Lexical units are demarcated by changes in the character set, so any continuous string of letters is considered one unit, any continuous string of numbers is considered one unit. The main complication arises from the fact that dots ('.') can be used both as separators (e.g. "Sep.20.2009") or decimal points (e.g. "4:30:21.447"). As such, it is necessary to read the full context of any dot-separated strings before breaking it into tokens; as such, this function maintains a "token stack", for when the ambiguous context demands that multiple tokens be parsed at once. rFNrTa0 .a.,0.z.,r')r#r&r')rpoprrrriswordisnumisspaceappendlencount_split_decimalsplitreplace)rZ seenletterstokenstatenextcharltokrrr get_tokenDs              "         z_timelex.get_tokencCs|S)Nr)rrrr__iter__sz_timelex.__iter__cCs|j}|dkrt|S)N)r7 StopIteration)rr2rrr__next__sz_timelex.__next__cCs|jS)N)r:)rrrrnextsz _timelex.nextcCs t||S)N)list)clssrrrr0sz_timelex.splitcCs|jS)z5 Whether or not the next character is part of a word )isalpha)r=r4rrrr)sz_timelex.iswordcCs|jS)z0 Whether the next character is part of a number )isdigit)r=r4rrrr*sz_timelex.isnumcCs|jS)z* Whether the next character is whitespace )r+)r=r4rrrr+sz_timelex.isspaceN)r __module__ __qualname__recompiler/rr7r8r:r; classmethodr0r)r*r+rrrrr 0s m   r c@s,eZdZddZddZddZddZd S) _resultbasecCs x|jD]}t||dqWdS)N) __slots__setattr)rattrrrrrs z_resultbase.__init__cCsNg}x6|jD],}t||}|dk r |jd|t|fq Wd|dj|fS)Nz%s=%sz%s(%s)z, )rGrr,reprjoin)rZ classnamer5rIvaluerrr_reprs   z_resultbase._reprcstfddjDS)Nc3s|]}t|dk VqdS)N)r).0rI)rrr sz&_resultbase.__len__..)sumrG)rr)rr__len__s z_resultbase.__len__cCs|j|jjS)N)rMrr)rrrr__repr__sz_resultbase.__repr__N)rrArBrrMrQrRrrrrrFsrFc@seZdZdZdddddddd d d d d ddddddgZdcdddedfdgdhdigZdjdkdldmdndodpdqdrdsdtdug ZdvdwdxgZdydzgZdFdGdHgZ dgZ iZ d{dJdKZ dLdMZ dNdOZdPdQZdRdSZdTdUZdVdWZdXdYZdZd[Zd\d]Zd|d^d_Zd`daZdbS)}r a Class which handles what inputs are accepted. Subclass this to customize the language and acceptable values for each parameter. :param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day (``True``) or month (``False``). If ``yearfirst`` is set to ``True``, this distinguishes between YDM and YMD. Default is ``False``. :param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the year. If ``True``, the first number is taken to be the year, otherwise the last number is taken to be the year. Default is ``False``. r!r"r$;-/'ZatZonandZadmtZofstZndZrdZthMonMondayTueTuesdayWed WednesdayThuThursdayFriFridaySatSaturdaySunSundayJanJanuaryFebFebruaryMarMarchAprAprilMayJunJuneJulJulyAugAugustSepSept SeptemberOctOctoberNovNovemberDecDecemberhhourhoursminuteminutesr>secondsecondsamrpmpUTCZGMTZFcCs|j|j|_|j|j|_|j|j|_|j|j|_|j|j |_ |j|j |_ |j|j |_||_||_tjj|_|jdd|_dS)Nd)_convertJUMP_jumpWEEKDAYS _weekdaysMONTHS_monthsHMS_hmsAMPM_ampmUTCZONE_utczonePERTAIN_pertaindayfirst yearfirsttimeZ localtimeZtm_year_year_century)rrrrrrrs zparserinfo.__init__cCsPi}xFt|D]:\}}t|tr.)r-minrkeysrKeyError)rrrrrweekday7s  zparserinfo.weekdayc CsLt|tdd|jjDkrHy|j|jdStk rFYnXdS)Ncss|]}t|VqdS)N)r-)rNrrrrrO@sz#parserinfo.month..r)r-rrrrr)rrrrrmonth?s  zparserinfo.monthc Cs(y|j|jStk r"dSXdS)N)rrr)rrrrrhmsGszparserinfo.hmsc Cs(y|j|jStk r"dSXdS)N)rrr)rrrrrampmMszparserinfo.ampmcCs|j|jkS)N)rr)rrrrrpertainSszparserinfo.pertaincCs|j|jkS)N)rr)rrrrrutczoneVszparserinfo.utczonecCs||jkrdS|jj|S)Nr)rTZOFFSETget)rrrrrtzoffsetYs zparserinfo.tzoffsetcCsJ|dkrF| rF||j7}t||jdkrF||jkr>|d7}n|d8}|S)Nr2)rabsr)ryearcentury_specifiedrrr convertyear_s   zparserinfo.convertyearcCsl|jdk r|j|j|j|_|jdkr.|j s8|jdkrFd|_d|_n"|jdkrh|jrh|j|jrhd|_dS)NrrrT)rrrrtznamer)rresrrrvalidateis zparserinfo.validateN)r[r\)r]r^)r_r`)rarb)rcrd)rerf)rgrh)rirj)rkrl)rmrn)rorp)rqrq)rrrs)rtru)rvrw)rxryrz)r{r|)r}r~)rr)rrr)rXrr)r>rr)rr)rr)FF)F)rrArB__doc__rrrrrrrrrrrrrrrrrrrrrrrrr sV     csPeZdZfddZeddZeddZddZfd d Zd d Z Z S) _ymdcs$t|j|j||d|_||_dS)NF)superrrrtzstr)rrargskwargs)rrrrwsz _ymd.__init__c Cs&y t||kStk r dSXdS)NF)int ValueError)r2rrrrtoken_could_be_year|s z_ymd.token_could_be_yearcsfdd|DS)Ncsg|]}tj|r|qSr)rr)rNr2)rrr sz3_ymd.find_potential_year_tokens..r)rtokensr)rrfind_potential_year_tokenssz_ymd.find_potential_year_tokenscCsFx@t|D]4\}}tj||}t|dkr t|ddkr |Sq WdS)zk attempt to deduce if a pre 100 year was lost due to padded zeros being taken off rrr%N)rrrr-)rrindexr2Zpotential_year_tokensrrrfind_probable_year_indexs z_ymd.find_probable_year_indexcsNt|dr&|jr4t|dkr4d|_n|dkr4d|_t|j|jt|dS)NrQr%Tr)hasattrr@r-rrrr,r)rval)rrrr,s  z _ymd.appendcCs,t|}d\}}}|dkr&tdn|dks>|d kr|dkr|d krT||}||=|dksd|d kr|ddkrz|d}n|d}n|dkr|ddkr|\}}n8|ddkr|\}}n"|r|ddkr|\}}n|\}}nB|dkr"|dkr|\}}}n |dkrF|ddks.|r:|ddkr:|\}}}n |\}}}n|dkrv|ddkrj|\}}}n |\}}}n|ddks|jtj|jdks|r|ddkr|ddkr|r|ddkr|\}}}n |\}}}n8|ddks |r|ddkr|\}}}n |\}}}|||fS) NzMore than three YMD valuesrr%r )NNNr'r'r')r-rrr r0r)rmstridxrrZlen_ymdrrdayrrr resolve_ymdsR              "     "  "  z_ymd.resolve_ymd) rrArBr staticmethodrrrr,r __classcell__rr)rrrvs     rc@sFeZdZd ddZdddZGdddeZdd d Zed d Z dS)parserNcCs|pt|_dS)N)r info)rrrrrrszparser.__init__FcKsV|dkr tjjjddddd}|j|f|\}}|dkrBtdt|dkrVtdi}x&dD]} t|| } | dk r`| || <q`Wd|kr|jdkr|jn|j} |jdkr|jn|j} |j dkr|j n|j } | t | | d krt | | d |d<|jf|}|j dk r$|j r$|t j |j d}|s8t |tjsJ|r|j|krt |tjrh||j|j}n |j|j}t |tjr|}n|jdkr|jtjd}n |jr8|jtj|j|jd}|jddrN||fS|SdS)aV Parse the date/time string into a :class:`datetime.datetime` object. :param timestr: Any date/time string using the supported formats. :param default: The default datetime object, if this is a datetime object and not ``None``, elements specified in ``timestr`` replace elements in the default object. :param ignoretz: If set ``True``, time zones in parsed strings are ignored and a naive :class:`datetime.datetime` object is returned. :param tzinfos: Additional time zone names / aliases which may be present in the string. This argument maps time zone names (and optionally offsets from those time zones) to time zones. This parameter can be a dictionary with timezone aliases mapping time zone names to time zones or a function taking two parameters (``tzname`` and ``tzoffset``) and returning a time zone. The timezones to which the names are mapped can be an integer offset from UTC in minutes or a :class:`tzinfo` object. .. doctest:: :options: +NORMALIZE_WHITESPACE >>> from dateutil.parser import parse >>> from dateutil.tz import gettz >>> tzinfos = {"BRST": -10800, "CST": gettz("America/Chicago")} >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -10800)) >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) This parameter is ignored if ``ignoretz`` is set. :param **kwargs: Keyword arguments as passed to ``_parse()``. :return: Returns a :class:`datetime.datetime` object or, if the ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the first element being a :class:`datetime.datetime` object, the second a tuple containing the fuzzy tokens. :raises ValueError: Raised for invalid or unknown string format, if the provided :class:`tzinfo` is not in a valid format, or if an invalid date would be created. :raises TypeError: Raised for non-string or character stream input. :raises OverflowError: Raised if the parsed date exceeds the largest valid C integer on your system. Nr)rrr microsecondzUnknown string formatzString does not contain a date.rrrrrrrr)rz9Offset must be tzinfo subclass, tz string, or int offset.)tzinfofuzzy_with_tokensF)rrrrrrr)datetimeZnowr1_parserr-rrrrrrr r collectionsCallablerrrrrr rrrZtzlocalZtzutc)rtimestrdefaultZignoretzZtzinfosrrskipped_tokensreplrIrLZcyearZcmonthZcdayretZtzdatarrrrr s\?          z parser.parsec @s&eZdZddddddddd d d g Zd S) zparser._resultrrrrrrrrrrrN)rrArBrGrrrr_resultisrcCst |rd}|j}|dkr|j}|dkr*|j}|j}tj|}d } t} yt|} d!} t|} d} xt|| k ry||}t |}Wnt k rd}YnX|dk rt||}|d7}t| dkrH|d"krH|j dkrH|| ks ||dkrH|j ||dkrH||d}t |dd|_ |dkrt |dd|_qf|d kst|d kr||djd d kr||d}| r||djd d#kr| j|dd| j|dd| j|ddn>> from dateutil.parser import parse >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) TNr%rrr:r"r r!<rTrUFzNo hour specified with zAM or PM flag.zInvalid hour specified for z12-hour clock.cSsg|]}|tjkr|qSr)stringascii_uppercase)rNxrrrrsz!parser._parse..+i()cSsg|]}|tjkr|qSr)rr)rNrrrrrsr')r%rr')rrr)rTrUr"r')NNr')NNr')rTrUz%No hour specified with AM or PM flag.z)Invalid hour specified for 12-hour clock.)rrT)rrT)rrTr')r'r)NN)NN)NN)NN)'rrrrr r0r<rr-floatrrrrrfindr,_parsemsrrrrAssertionErrorrrrstrr _skip_tokenrrrrrrr IndexErrorrr)rrrrZfuzzyrrrr5last_skipped_token_irZymdrlen_lrZ value_reprrLlen_lir>idxZnewidxZ sec_remaindersepZ val_is_ampmsignalrrrrrrrns)     $  ,                                 & $$            2       4 &   .&        z parser._parsecCs8||dkr"|d||7<n|j|||}|S)Nrr')r,)rrrr5rrrr-s  zparser._skip_token)N)NFN)NNFF) rrArBrr rFrrrrrrrrrs   ArcKs(|rt|j|f|Stj|f|SdS)a) Parse a string in one of the supported formats, using the ``parserinfo`` parameters. :param timestr: A string containing a date/time stamp. :param parserinfo: A :class:`parserinfo` object containing parameters for the parser. If ``None``, the default arguments to the :class:`parserinfo` constructor are used. The ``**kwargs`` parameter takes the following keyword arguments: :param default: The default datetime object, if this is a datetime object and not ``None``, elements specified in ``timestr`` replace elements in the default object. :param ignoretz: If set ``True``, time zones in parsed strings are ignored and a naive :class:`datetime` object is returned. :param tzinfos: Additional time zone names / aliases which may be present in the string. This argument maps time zone names (and optionally offsets from those time zones) to time zones. This parameter can be a dictionary with timezone aliases mapping time zone names to time zones or a function taking two parameters (``tzname`` and ``tzoffset``) and returning a time zone. The timezones to which the names are mapped can be an integer offset from UTC in minutes or a :class:`tzinfo` object. .. doctest:: :options: +NORMALIZE_WHITESPACE >>> from dateutil.parser import parse >>> from dateutil.tz import gettz >>> tzinfos = {"BRST": -10800, "CST": gettz("America/Chicago")} >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -10800)) >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) This parameter is ignored if ``ignoretz`` is set. :param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day (``True``) or month (``False``). If ``yearfirst`` is set to ``True``, this distinguishes between YDM and YMD. If set to ``None``, this value is retrieved from the current :class:`parserinfo` object (which itself defaults to ``False``). :param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the year. If ``True``, the first number is taken to be the year, otherwise the last number is taken to be the year. If this is set to ``None``, the value is retrieved from the current :class:`parserinfo` object (which itself defaults to ``False``). :param fuzzy: Whether to allow fuzzy parsing, allowing for string like "Today is January 1, 2047 at 8:21:00AM". :param fuzzy_with_tokens: If ``True``, ``fuzzy`` is automatically set to True, and the parser will return a tuple where the first element is the parsed :class:`datetime.datetime` datetimestamp and the second element is a tuple containing the portions of the string which were ignored: .. doctest:: >>> from dateutil.parser import parse >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) :return: Returns a :class:`datetime.datetime` object or, if the ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the first element being a :class:`datetime.datetime` object, the second a tuple containing the fuzzy tokens. :raises ValueError: Raised for invalid or unknown string format, if the provided :class:`tzinfo` is not in a valid format, or if an invalid date would be created. :raises OverflowError: Raised if the parsed date exceeds the largest valid C integer on your system. N)rr DEFAULTPARSER)rr rrrrr <s_c@s$eZdZGdddeZddZdS) _tzparserc@s<eZdZddddddgZGdddeZd d Zd d Zd S)z_tzparser._resultstdabbr stdoffsetdstabbr dstoffsetstartendc@seZdZdddddddgZdS) z_tzparser._result._attrrweekrydayjydayrrN)rrArBrGrrrr_attrsr cCs |jdS)N)rM)rrrrrRsz_tzparser._result.__repr__cCs"tj||j|_|j|_dS)N)rFrr rr)rrrrrs  z_tzparser._result.__init__N)rrArBrGrFr rRrrrrrrs rc CsZ|j}tj|}y$t|}d}x||kr|}x(||kr\dd||D r\|d7}q6W||kr|jsd}dj||||_nd}dj||||_|}||ko||dks||dd kr||dkrd||dk}|d7}nd }t||} | d krJt||t||dd d t||d dd|n|d|kr||ddkrt||t||d t||d d||d 7}n4| d krt||t||dd d |ndS|d7}|jrPq&Pq&W||krBx*t ||D]}||dkrd||<qW||dks:t |d7}||krPnd|j dkojdknrdd||dD rx|j |j fD]} t||| _|d 7}||d krt||dd!} |d7}n t||} |d 7}| r| | _t||dd| _nt||| _|d 7}t||| _|d 7}qW||kr6||d"kr|d$||dk}|d7}nd}|jt||||_n|j dd kr6||dj dd kr6dd||dD r6xF|j |j fD]4} ||dkr|d7}t||| _n||dkr|d7}t||| _|d7}||d%ksXt |d7}t||| _| jdkrd&| _|d7}||d'kst |d7}t||dd| _nt||d| _|d7}||kr||dkr|d7}t||} | d kr>t||dd d t||d dd| _n|d|kr||ddkrt||d t||d d| _|d 7}|d|kr||ddkr|d 7}| jt||7_n*| d krt||dd d | _ndS|d7}||ks||dkst |d7}qW||ks6t Wnttt fk rTdSX|S)(NrcSsg|]}|dkr|qS)z0123456789:,-+r)rNrrrrrsz#_tzparser.parse..rrr rrrT 0123456789rr%irrrSr$r cSs*g|]"}|dkr|D]}|dkr|qqS)r$rr)rNryrrrrs rUc Ss*g|]"}|dkr|D]}|dkr|qqS) r$rUJMr"rTrr)r$rUrrr"rTrr)rNrrrrrrsrrr"r)rrT)rrTr')rr'r'r')rTrr')r'r)rTr"r')rTr")rr r0r-rrKrrHrrangerr.rrrr rrrrrr r rr) rrrr5rrjZoffattrrrrrLrrrr s      " *     "    (   4 &  z_tzparser.parseN)rrArBrFrr rrrrrsrcCs tj|S)N)DEFAULTTZPARSERr )rrrr_parsetzQsrcCsFd|krt|dfS|jd\}}t|t|jddddfSdS)z9Parse a I[.F] seconds value into (seconds, microseconds).r"rrr N)rr0ljust)rLrfrrrrUs r)N)!rZ __future__rrrrrrCiorZcalendarrZsixrrrr r r __all__objectr rFr r<rrrr rrrrrrrrs<     #oX e.