ISO 8601 compliant parser.

    :param text: The string to parse
    :type text: str

    :rtype: datetime.datetime or datetime.time or datetime.date
424510
def parse_iso8601(text):
    
    parsed = _parse_iso8601_duration(text)
    if parsed is not None:
        return parsed

    m = ISO8601_DT.match(text)
    if not m:
        raise ParserError("Invalid ISO 8601 string")

    ambiguous_date = False
    is_date = False
    is_time = False
    year = 0
    month = 1
    day = 1
    minute = 0
    second = 0
    microsecond = 0
    tzinfo = None

    if m:
        if m.group("date"):
            # A date has been specified
            is_date = True

            if m.group("isocalendar"):
                # We have a ISO 8601 string defined
                # by week number
                if (
                    m.group("weeksep")
                    and not m.group("weekdaysep")
                    and m.group("isoweekday")
                ):
                    raise ParserError("Invalid date string: {}".format(text))

                if not m.group("weeksep") and m.group("weekdaysep"):
                    raise ParserError("Invalid date string: {}".format(text))

                try:
                    date = _get_iso_8601_week(
                        m.group("isoyear"), m.group("isoweek"), m.group("isoweekday")
                    )
                except ParserError:
                    raise
                except ValueError:
                    raise ParserError("Invalid date string: {}".format(text))

                year = date["year"]
                month = date["month"]
                day = date["day"]
            else:
                # We have a classic date representation
                year = int(m.group("year"))

                if not m.group("monthday"):
                    # No month and day
                    month = 1
                    day = 1
                else:
                    if m.group("month") and m.group("day"):
                        # Month and day
                        if not m.group("daysep") and len(m.group("day")) == 1:
                            # Ordinal day
                            ordinal = int(m.group("month") + m.group("day"))
                            leap = is_leap(year)
                            months_offsets = MONTHS_OFFSETS[leap]

                            if ordinal > months_offsets[13]:
                                raise ParserError("Ordinal day is out of range")

                            for i in range(1, 14):
                                if ordinal <= months_offsets[i]:
                                    day = ordinal - months_offsets[i - 1]
                                    month = i - 1

                                    break
                        else:
                            month = int(m.group("month"))
                            day = int(m.group("day"))
                    else:
                        # Only month
                        if not m.group("monthsep"):
                            # The date looks like 201207
                            # which is invalid for a date
                            # But it might be a time in the form hhmmss
                            ambiguous_date = True

                        month = int(m.group("month"))
                        day = 1

        if not m.group("time"):
            # No time has been specified
            if ambiguous_date:
                # We can "safely" assume that the ambiguous date
                # was actually a time in the form hhmmss
                hhmmss = "{}{:0>2}".format(str(year), str(month))

                return datetime.time(int(hhmmss[:2]), int(hhmmss[2:4]), int(hhmmss[4:]))

            return datetime.date(year, month, day)

        if ambiguous_date:
            raise ParserError("Invalid date string: {}".format(text))

        if is_date and not m.group("timesep"):
            raise ParserError("Invalid date string: {}".format(text))

        if not is_date:
            is_time = True

        # Grabbing hh:mm:ss
        hour = int(m.group("hour"))
        minsep = m.group("minsep")

        if m.group("minute"):
            minute = int(m.group("minute"))
        elif minsep:
            raise ParserError("Invalid ISO 8601 time part")

        secsep = m.group("secsep")
        if secsep and not minsep and m.group("minute"):
            # minute/second separator but no hour/minute separator
            raise ParserError("Invalid ISO 8601 time part")

        if m.group("second"):
            if not secsep and minsep:
                # No minute/second separator but hour/minute separator
                raise ParserError("Invalid ISO 8601 time part")

            second = int(m.group("second"))
        elif secsep:
            raise ParserError("Invalid ISO 8601 time part")

        # Grabbing subseconds, if any
        if m.group("subsecondsection"):
            # Limiting to 6 chars
            subsecond = m.group("subsecond")[:6]

            microsecond = int("{:0<6}".format(subsecond))

        # Grabbing timezone, if any
        tz = m.group("tz")
        if tz:
            if tz == "Z":
                offset = 0
            else:
                negative = True if tz.startswith("-") else False
                tz = tz[1:]
                if ":" not in tz:
                    if len(tz) == 2:
                        tz = "{}00".format(tz)

                    off_hour = tz[0:2]
                    off_minute = tz[2:4]
                else:
                    off_hour, off_minute = tz.split(":")

                offset = ((int(off_hour) * 60) + int(off_minute)) * 60

                if negative:
                    offset = -1 * offset

            tzinfo = FixedTimezone(offset)

        if is_time:
            return datetime.time(hour, minute, second, microsecond)

        return datetime.datetime(
            year, month, day, hour, minute, second, microsecond, tzinfo=tzinfo
        )
304689
def iso_string_to_python_datetime(
        isostring: str) -> Optional[datetime.datetime]:
    
    if not isostring:
        return None  # if you parse() an empty string, you get today's date
    return dateutil.parser.parse(isostring)
1292856
def parse(self, text):
        
        self.scripts.append(kurt.text.parse(text, self))
851199
def from_text(text):
        
        number = int(filter(unicode.isdigit, unicode(text)))
        return Phone(number=number)
721177
def parse_datetime(__string: str) -> datetime.datetime:
    
    if not __string:
        datetime_ = datetime.datetime.now(datetime.timezone.utc)
    else:
        # pylint: disable=no-member
        datetime_ = ciso8601.parse_datetime(__string)
    if datetime_.tzinfo is None:
        datetime_ = datetime_.replace(tzinfo=datetime.timezone.utc)
    return datetime_
1036035
protected T parseString(final DateFormat formatter, final String text) throws ParseException {
        Date date = formatter.parse(text);
        return convertTypeValue(date);
    }
1252966
def _parse_date(string: str) -> datetime.date:
    
    return datetime.datetime.strptime(string, '%Y-%m-%d').date()
372967
def parse_datetime(text: str, date_format: str=None,
                   is_day_period: Optional[bool]=None,
                   datetime_now: datetime.datetime=None) \
        -> Tuple[datetime.datetime, int, int]:
    ''''''
    datetime_now = datetime_now or \
        datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
    year = datetime_now.year
    month = datetime_now.month
    day = datetime_now.day
    hour = 0
    minute = 0
    second = 0
    date_ok = False
    start_index = float('+inf')
    end_index = float('-inf')
    ambiguous_year = False

    text = unicodedata.normalize('NFKD', text).lower()

    # Let's do time first
    match = TIME_PATTERN.search(text)

    if match:
        hour_str = match.group(1)
        hour = int(hour_str)
        minute = int(match.group(2))
        day_period = match.group(4)

        if match.group(3):
            second = int(match.group(3))

        if day_period and is_day_period and hour < 13:
            if day_period.lower() in PM_STRINGS:
                if hour != 12:
                    hour += 12
            elif hour == 12:
                hour = 0

        start_index = match.start()
        end_index = match.end()

    # Now try dates
    if date_format == 'ymd' or not date_format:
        match = ISO_8601_DATE_PATTERN.search(text)
        if match:
            date_ok = True
            year = int(match.group(1))
            month = int(match.group(2))
            day = int(match.group(3))

            start_index = min(start_index, match.start())
            end_index = max(end_index, match.end())

    if not date_ok and (date_format == 'mdy' or not date_format):
        match = MMM_DD_YY_PATTERN.search(text)
        if match:
            date_ok = True
            month_str = match.group(1)
            month = parse_month(month_str)
            day = int(match.group(2))
            year_str = match.group(3)

            if year_str and len(year_str) == 4:
                year = int(year_str)
            else:
                ambiguous_year = True

            start_index = min(start_index, match.start())
            end_index = max(end_index, match.end())

    if not date_ok:
        match = NN_NN_NNNN_PATTERN.search(text)
        if match:
            date_ok = True
            num_1 = int(match.group(1))
            num_2 = int(match.group(2))
            year = int(match.group(3))

            if year < 100:
                year = y2k(year)

            if date_format == 'mdy' or num_2 > 12:
                month = num_1
                day = num_2
            else:
                day = num_1
                month = num_2

            start_index = min(start_index, match.start())
            end_index = max(end_index, match.end())

    if date_ok:
        guess_date = datetime.datetime(year, month, day, hour, minute, second,
                                       tzinfo=datetime.timezone.utc)

        if ambiguous_year and guess_date > datetime_now:
            # Sometimes year is not shown within 6 months
            # Year is shown for dates in the future
            guess_date = guess_date.replace(year=year - 1)

        return guess_date, start_index, end_index

    else:
        raise ValueError('Failed to parse date from {}'.format(repr(text)))
383732
def parse_value(self, text: str) -> Optional[bool]:
        
        if text == "true":
            return True
        if text == "false":
            return False
1067002
def from_ISO_8601(cls, date_string, time_string, tz_string):
        
        # parse tz_string
        if tz_string:
            tz_offset = (int(tz_string[1:3]) * 60) + int(tz_string[3:])
            if tz_string[0] == '-':
                tz_offset = -tz_offset
        else:
            tz_offset = None
        if time_string == '000000':
            # assume no time information
            time_string = ''
            tz_offset = None
        datetime_string = date_string + time_string[:13]
        precision = min((len(datetime_string) - 2) // 2, 7)
        if precision <= 0:
            return None
        fmt = ''.join(('%Y', '%m', '%d', '%H', '%M', '%S', '.%f')[:precision])
        return cls(
            (datetime.strptime(datetime_string, fmt), precision, tz_offset))
390945
def text_to_edtf(text):
    
    if not text:
        return

    t = text.lower()

    # try parsing the whole thing
    result = text_to_edtf_date(t)

    if not result:
        # split by list delims and move fwd with the first thing that returns a non-empty string.
        # TODO: assemble multiple dates into a {} or [] structure.
        for split in [",", ";", "or"]:
            for list_item in t.split(split):

                # try parsing as an interval - split by '-'
                toks = list_item.split("-")
                if len(toks) == 2:
                    d1 = toks[0].strip()
                    d2 = toks[1].strip()

                    # match looks from the beginning of the string, search
                    # looks anywhere.

                    if re.match(r'\d\D\b', d2):  # 1-digit year partial e.g. 1868-9
                        if re.search(r'\b\d\d\d\d$', d1):  # TODO: evaluate it and see if it's a year
                            d2 = d1[-4:-1] + d2
                    elif re.match(r'\d\d\b', d2):  # 2-digit year partial e.g. 1809-10
                        if re.search(r'\b\d\d\d\d$', d1):
                            d2 = d1[-4:-2] + d2
                    else:
                        century_range_match = re.search(r'\b(\d\d)(th|st|nd|rd|)-(\d\d)(th|st|nd|rd) [cC]', "%s-%s" % (d1,d2))
                        if century_range_match:
                            g = century_range_match.groups()
                            d1 = "%sC" % g[0]
                            d2 = "%sC" % g[2]

                    r1 = text_to_edtf_date(d1)
                    r2 = text_to_edtf_date(d2)

                    if r1 and r2:
                        result = r1 + "/" + r2
                        return result

                # is it an either/or year "1838/1862" - that has a different
                # representation in EDTF. If it's 'both', then we use {}. If
                # it's 'or' then we use []. Assuming the latter for now.
                # This whole section could be more friendly.

                else:
                    int_match = re.search(r"(\d\d\d\d)\/(\d\d\d\d)", list_item)
                    if int_match:
                        return "[%s, %s]" % (int_match.group(1), int_match.group(2))

                result = text_to_edtf_date(list_item)
                if result:
                    break
            if result:
                break

    is_before = re.findall(r'\bbefore\b', t)
    is_before = is_before or re.findall(r'\bearlier\b', t)

    is_after = re.findall(r'\bafter\b', t)
    is_after = is_after or re.findall(r'\bsince\b', t)
    is_after = is_after or re.findall(r'\blater\b', t)

    if is_before:
        result = u"unknown/%s" % result
    elif is_after:
        result = u"%s/unknown" % result

    return result
298460
def of_text(self, text, encoding="utf-8"):
        
        m = self.hash_algo()
        m.update(text.encode(encoding))
        if self.return_int:
            return int(m.hexdigest(), 16)
        else:
            return m.hexdigest()
758247
def parsetime(text):
    '''
    

    '''
    mins, maxs = text.split('-', 1)
    minv = s_time.parse(mins)
    maxv = s_time.parse(maxs, base=minv)
    return minv, maxv
1102120
def text(string, encoding='utf8'):
    
    if isinstance(string, six.text_type):
        return string
    elif isinstance(string, six.binary_type):
        return string.decode(encoding)
    else:
        return six.text_type(string)
953363
public static UtcOffset parse(String text) {
		Pattern timeZoneRegex = Pattern.compile("^([-\\+])?(\\d{1,2})(:?(\\d{2}))?(:?(\\d{2}))?$");
		Matcher m = timeZoneRegex.matcher(text);

		if (!m.find()) {
			throw Messages.INSTANCE.getIllegalArgumentException(21, text);
		}

		String signStr = m.group(1);
		boolean positive = !"-".equals(signStr);

		String hourStr = m.group(2);
		int hourOffset = Integer.parseInt(hourStr);

		String minuteStr = m.group(4);
		int minuteOffset = (minuteStr == null) ? 0 : Integer.parseInt(minuteStr);

		return new UtcOffset(positive, hourOffset, minuteOffset);
	}
619528
def parse(cls, text):
        
        OUTSIDE, IN_DOUBLE, IN_SINGLE = 0, 1, 2

        iterator = enumerate(text)
        state = OUTSIDE
        parts = []
        current_part = ''
        part_start_pos = 0

        for i, c in iterator:  # XXX: correctly handle empty strings.
            if state == OUTSIDE:
                if c.isspace():
                    # New part.
                    if current_part:
                        parts.append(current_part)
                    part_start_pos = i + 1
                    current_part = ''
                elif c == '"':
                    state = IN_DOUBLE
                elif c == "'":
                    state = IN_SINGLE
                else:
                    current_part += c

            elif state == IN_SINGLE:
                if c == "'":
                    state = OUTSIDE
                elif c == "\\":
                    next(iterator)
                    current_part += c
                else:
                    current_part += c

            elif state == IN_DOUBLE:
                if c == '"':
                    state = OUTSIDE
                elif c == "\\":
                    next(iterator)
                    current_part += c
                else:
                    current_part += c

        parts.append(current_part)
        return parts, part_start_pos
291500
def parse(text):
    
    ret = Docstring()
    if not text:
        return ret

    text = inspect.cleandoc(text)
    match = re.search('^:', text, flags=re.M)
    if match:
        desc_chunk = text[:match.start()]
        meta_chunk = text[match.start():]
    else:
        desc_chunk = text
        meta_chunk = ''

    parts = desc_chunk.split('\n', 1)
    ret.short_description = parts[0] or None
    if len(parts) > 1:
        long_desc_chunk = parts[1] or ''
        ret.blank_after_short_description = long_desc_chunk.startswith('\n')
        ret.blank_after_long_description = long_desc_chunk.endswith('\n\n')
        ret.long_description = long_desc_chunk.strip() or None

    for match in re.finditer(
            r'(^:.*?)(?=^:|\Z)', meta_chunk, flags=re.S | re.M
    ):
        chunk = match.group(0)
        if not chunk:
            continue
        try:
            args_chunk, desc_chunk = chunk.lstrip(':').split(':', 1)
        except ValueError:
            raise ParseError(
                'Error parsing meta information near "{}".'.format(chunk)
            )
        args = args_chunk.split()
        desc = desc_chunk.strip()
        if '\n' in desc:
            first_line, rest = desc.split('\n', 1)
            desc = first_line + '\n' + inspect.cleandoc(rest)
        ret.meta.append(DocstringMeta(args, description=desc, type=None))

    return ret