Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/dateutil/parser/isoparser.py
7758 views
# -*- coding: utf-8 -*-1"""2This module offers a parser for ISO-8601 strings34It is intended to support all valid date, time and datetime formats per the5ISO-8601 specification.67..versionadded:: 2.7.08"""9from datetime import datetime, timedelta, time, date10import calendar11from dateutil import tz1213from functools import wraps1415import re16import six1718__all__ = ["isoparse", "isoparser"]192021def _takes_ascii(f):22@wraps(f)23def func(self, str_in, *args, **kwargs):24# If it's a stream, read the whole thing25str_in = getattr(str_in, 'read', lambda: str_in)()2627# If it's unicode, turn it into bytes, since ISO-8601 only covers ASCII28if isinstance(str_in, six.text_type):29# ASCII is the same in UTF-830try:31str_in = str_in.encode('ascii')32except UnicodeEncodeError as e:33msg = 'ISO-8601 strings should contain only ASCII characters'34six.raise_from(ValueError(msg), e)3536return f(self, str_in, *args, **kwargs)3738return func394041class isoparser(object):42def __init__(self, sep=None):43"""44:param sep:45A single character that separates date and time portions. If46``None``, the parser will accept any single character.47For strict ISO-8601 adherence, pass ``'T'``.48"""49if sep is not None:50if (len(sep) != 1 or ord(sep) >= 128 or sep in '0123456789'):51raise ValueError('Separator must be a single, non-numeric ' +52'ASCII character')5354sep = sep.encode('ascii')5556self._sep = sep5758@_takes_ascii59def isoparse(self, dt_str):60"""61Parse an ISO-8601 datetime string into a :class:`datetime.datetime`.6263An ISO-8601 datetime string consists of a date portion, followed64optionally by a time portion - the date and time portions are separated65by a single character separator, which is ``T`` in the official66standard. Incomplete date formats (such as ``YYYY-MM``) may *not* be67combined with a time portion.6869Supported date formats are:7071Common:7273- ``YYYY``74- ``YYYY-MM`` or ``YYYYMM``75- ``YYYY-MM-DD`` or ``YYYYMMDD``7677Uncommon:7879- ``YYYY-Www`` or ``YYYYWww`` - ISO week (day defaults to 0)80- ``YYYY-Www-D`` or ``YYYYWwwD`` - ISO week and day8182The ISO week and day numbering follows the same logic as83:func:`datetime.date.isocalendar`.8485Supported time formats are:8687- ``hh``88- ``hh:mm`` or ``hhmm``89- ``hh:mm:ss`` or ``hhmmss``90- ``hh:mm:ss.ssssss`` (Up to 6 sub-second digits)9192Midnight is a special case for `hh`, as the standard supports both9300:00 and 24:00 as a representation. The decimal separator can be94either a dot or a comma.959697.. caution::9899Support for fractional components other than seconds is part of the100ISO-8601 standard, but is not currently implemented in this parser.101102Supported time zone offset formats are:103104- `Z` (UTC)105- `±HH:MM`106- `±HHMM`107- `±HH`108109Offsets will be represented as :class:`dateutil.tz.tzoffset` objects,110with the exception of UTC, which will be represented as111:class:`dateutil.tz.tzutc`. Time zone offsets equivalent to UTC (such112as `+00:00`) will also be represented as :class:`dateutil.tz.tzutc`.113114:param dt_str:115A string or stream containing only an ISO-8601 datetime string116117:return:118Returns a :class:`datetime.datetime` representing the string.119Unspecified components default to their lowest value.120121.. warning::122123As of version 2.7.0, the strictness of the parser should not be124considered a stable part of the contract. Any valid ISO-8601 string125that parses correctly with the default settings will continue to126parse correctly in future versions, but invalid strings that127currently fail (e.g. ``2017-01-01T00:00+00:00:00``) are not128guaranteed to continue failing in future versions if they encode129a valid date.130131.. versionadded:: 2.7.0132"""133components, pos = self._parse_isodate(dt_str)134135if len(dt_str) > pos:136if self._sep is None or dt_str[pos:pos + 1] == self._sep:137components += self._parse_isotime(dt_str[pos + 1:])138else:139raise ValueError('String contains unknown ISO components')140141if len(components) > 3 and components[3] == 24:142components[3] = 0143return datetime(*components) + timedelta(days=1)144145return datetime(*components)146147@_takes_ascii148def parse_isodate(self, datestr):149"""150Parse the date portion of an ISO string.151152:param datestr:153The string portion of an ISO string, without a separator154155:return:156Returns a :class:`datetime.date` object157"""158components, pos = self._parse_isodate(datestr)159if pos < len(datestr):160raise ValueError('String contains unknown ISO ' +161'components: {!r}'.format(datestr.decode('ascii')))162return date(*components)163164@_takes_ascii165def parse_isotime(self, timestr):166"""167Parse the time portion of an ISO string.168169:param timestr:170The time portion of an ISO string, without a separator171172:return:173Returns a :class:`datetime.time` object174"""175components = self._parse_isotime(timestr)176if components[0] == 24:177components[0] = 0178return time(*components)179180@_takes_ascii181def parse_tzstr(self, tzstr, zero_as_utc=True):182"""183Parse a valid ISO time zone string.184185See :func:`isoparser.isoparse` for details on supported formats.186187:param tzstr:188A string representing an ISO time zone offset189190:param zero_as_utc:191Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones192193:return:194Returns :class:`dateutil.tz.tzoffset` for offsets and195:class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is196specified) offsets equivalent to UTC.197"""198return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc)199200# Constants201_DATE_SEP = b'-'202_TIME_SEP = b':'203_FRACTION_REGEX = re.compile(b'[\\.,]([0-9]+)')204205def _parse_isodate(self, dt_str):206try:207return self._parse_isodate_common(dt_str)208except ValueError:209return self._parse_isodate_uncommon(dt_str)210211def _parse_isodate_common(self, dt_str):212len_str = len(dt_str)213components = [1, 1, 1]214215if len_str < 4:216raise ValueError('ISO string too short')217218# Year219components[0] = int(dt_str[0:4])220pos = 4221if pos >= len_str:222return components, pos223224has_sep = dt_str[pos:pos + 1] == self._DATE_SEP225if has_sep:226pos += 1227228# Month229if len_str - pos < 2:230raise ValueError('Invalid common month')231232components[1] = int(dt_str[pos:pos + 2])233pos += 2234235if pos >= len_str:236if has_sep:237return components, pos238else:239raise ValueError('Invalid ISO format')240241if has_sep:242if dt_str[pos:pos + 1] != self._DATE_SEP:243raise ValueError('Invalid separator in ISO string')244pos += 1245246# Day247if len_str - pos < 2:248raise ValueError('Invalid common day')249components[2] = int(dt_str[pos:pos + 2])250return components, pos + 2251252def _parse_isodate_uncommon(self, dt_str):253if len(dt_str) < 4:254raise ValueError('ISO string too short')255256# All ISO formats start with the year257year = int(dt_str[0:4])258259has_sep = dt_str[4:5] == self._DATE_SEP260261pos = 4 + has_sep # Skip '-' if it's there262if dt_str[pos:pos + 1] == b'W':263# YYYY-?Www-?D?264pos += 1265weekno = int(dt_str[pos:pos + 2])266pos += 2267268dayno = 1269if len(dt_str) > pos:270if (dt_str[pos:pos + 1] == self._DATE_SEP) != has_sep:271raise ValueError('Inconsistent use of dash separator')272273pos += has_sep274275dayno = int(dt_str[pos:pos + 1])276pos += 1277278base_date = self._calculate_weekdate(year, weekno, dayno)279else:280# YYYYDDD or YYYY-DDD281if len(dt_str) - pos < 3:282raise ValueError('Invalid ordinal day')283284ordinal_day = int(dt_str[pos:pos + 3])285pos += 3286287if ordinal_day < 1 or ordinal_day > (365 + calendar.isleap(year)):288raise ValueError('Invalid ordinal day' +289' {} for year {}'.format(ordinal_day, year))290291base_date = date(year, 1, 1) + timedelta(days=ordinal_day - 1)292293components = [base_date.year, base_date.month, base_date.day]294return components, pos295296def _calculate_weekdate(self, year, week, day):297"""298Calculate the day of corresponding to the ISO year-week-day calendar.299300This function is effectively the inverse of301:func:`datetime.date.isocalendar`.302303:param year:304The year in the ISO calendar305306:param week:307The week in the ISO calendar - range is [1, 53]308309:param day:310The day in the ISO calendar - range is [1 (MON), 7 (SUN)]311312:return:313Returns a :class:`datetime.date`314"""315if not 0 < week < 54:316raise ValueError('Invalid week: {}'.format(week))317318if not 0 < day < 8: # Range is 1-7319raise ValueError('Invalid weekday: {}'.format(day))320321# Get week 1 for the specific year:322jan_4 = date(year, 1, 4) # Week 1 always has January 4th in it323week_1 = jan_4 - timedelta(days=jan_4.isocalendar()[2] - 1)324325# Now add the specific number of weeks and days to get what we want326week_offset = (week - 1) * 7 + (day - 1)327return week_1 + timedelta(days=week_offset)328329def _parse_isotime(self, timestr):330len_str = len(timestr)331components = [0, 0, 0, 0, None]332pos = 0333comp = -1334335if len_str < 2:336raise ValueError('ISO time too short')337338has_sep = False339340while pos < len_str and comp < 5:341comp += 1342343if timestr[pos:pos + 1] in b'-+Zz':344# Detect time zone boundary345components[-1] = self._parse_tzstr(timestr[pos:])346pos = len_str347break348349if comp == 1 and timestr[pos:pos+1] == self._TIME_SEP:350has_sep = True351pos += 1352elif comp == 2 and has_sep:353if timestr[pos:pos+1] != self._TIME_SEP:354raise ValueError('Inconsistent use of colon separator')355pos += 1356357if comp < 3:358# Hour, minute, second359components[comp] = int(timestr[pos:pos + 2])360pos += 2361362if comp == 3:363# Fraction of a second364frac = self._FRACTION_REGEX.match(timestr[pos:])365if not frac:366continue367368us_str = frac.group(1)[:6] # Truncate to microseconds369components[comp] = int(us_str) * 10**(6 - len(us_str))370pos += len(frac.group())371372if pos < len_str:373raise ValueError('Unused components in ISO string')374375if components[0] == 24:376# Standard supports 00:00 and 24:00 as representations of midnight377if any(component != 0 for component in components[1:4]):378raise ValueError('Hour may only be 24 at 24:00:00.000')379380return components381382def _parse_tzstr(self, tzstr, zero_as_utc=True):383if tzstr == b'Z' or tzstr == b'z':384return tz.UTC385386if len(tzstr) not in {3, 5, 6}:387raise ValueError('Time zone offset must be 1, 3, 5 or 6 characters')388389if tzstr[0:1] == b'-':390mult = -1391elif tzstr[0:1] == b'+':392mult = 1393else:394raise ValueError('Time zone offset requires sign')395396hours = int(tzstr[1:3])397if len(tzstr) == 3:398minutes = 0399else:400minutes = int(tzstr[(4 if tzstr[3:4] == self._TIME_SEP else 3):])401402if zero_as_utc and hours == 0 and minutes == 0:403return tz.UTC404else:405if minutes > 59:406raise ValueError('Invalid minutes in time zone offset')407408if hours > 23:409raise ValueError('Invalid hours in time zone offset')410411return tz.tzoffset(None, mult * (hours * 60 + minutes) * 60)412413414DEFAULT_ISOPARSER = isoparser()415isoparse = DEFAULT_ISOPARSER.isoparse416417418