Extract datetime objects from a string of text.
187505
def datetime_parsing(text, base_date=datetime.now()):
    
    matches = []
    found_array = []

    # Find the position in the string
    for expression, function in regex:
        for match in expression.finditer(text):
            matches.append((match.group(), function(match, base_date), match.span()))

    # Wrap the matched text with TAG element to prevent nested selections
    for match, value, spans in matches:
        subn = re.subn(
            '(?!<TAG[^>]*?>)' + match + '(?![^<]*?</TAG>)', '<TAG>' + match + '</TAG>', text
        )
        text = subn[0]
        is_substituted = subn[1]
        if is_substituted != 0:
            found_array.append((match, value, spans))

    # To preserve order of the match, sort based on the start position
    return sorted(found_array, key=lambda match: match and match[2][0])
364455
def from_str(string):
        
        match = re.match(r'^UPDATE (.+)$', string)
        if match:
            parsed_date = dateutil.parser.parse(match.group(1), ignoretz=True)
            return UpdateEvent(parsed_date)
        else:
            raise EventParseError
1195715
def _parse(text, **options):
    
    # Handling special cases
    if text == "now":
        return pendulum.now()

    parsed = base_parse(text, **options)

    if isinstance(parsed, datetime.datetime):
        return pendulum.datetime(
            parsed.year,
            parsed.month,
            parsed.day,
            parsed.hour,
            parsed.minute,
            parsed.second,
            parsed.microsecond,
            tz=parsed.tzinfo or options.get("tz", UTC),
        )

    if isinstance(parsed, datetime.date):
        return pendulum.date(parsed.year, parsed.month, parsed.day)

    if isinstance(parsed, datetime.time):
        return pendulum.time(
            parsed.hour, parsed.minute, parsed.second, parsed.microsecond
        )

    if isinstance(parsed, _Interval):
        if parsed.duration is not None:
            duration = parsed.duration

            if parsed.start is not None:
                dt = pendulum.instance(parsed.start, tz=options.get("tz", UTC))

                return pendulum.period(
                    dt,
                    dt.add(
                        years=duration.years,
                        months=duration.months,
                        weeks=duration.weeks,
                        days=duration.remaining_days,
                        hours=duration.hours,
                        minutes=duration.minutes,
                        seconds=duration.remaining_seconds,
                        microseconds=duration.microseconds,
                    ),
                )

            dt = pendulum.instance(parsed.end, tz=options.get("tz", UTC))

            return pendulum.period(
                dt.subtract(
                    years=duration.years,
                    months=duration.months,
                    weeks=duration.weeks,
                    days=duration.remaining_days,
                    hours=duration.hours,
                    minutes=duration.minutes,
                    seconds=duration.remaining_seconds,
                    microseconds=duration.microseconds,
                ),
                dt,
            )

        return pendulum.period(
            pendulum.instance(parsed.start, tz=options.get("tz", UTC)),
            pendulum.instance(parsed.end, tz=options.get("tz", UTC)),
        )

    if CDuration and isinstance(parsed, CDuration):
        return pendulum.duration(
            years=parsed.years,
            months=parsed.months,
            weeks=parsed.weeks,
            days=parsed.days,
            hours=parsed.hours,
            minutes=parsed.minutes,
            seconds=parsed.seconds,
            microseconds=parsed.microseconds,
        )

    return parsed
150023
def parse(d):
    
    res = {}
    for k, v in iteritems(d):
        if isinstance(v, string_types) and DATETIME_ISO_FORMAT.match(v):
            v = dateutil.parser.parse(v)
        res[k] = v
    return res
1252966
def _parse_date(string: str) -> datetime.date:
    
    return datetime.datetime.strptime(string, '%Y-%m-%d').date()
666490
def _read_date_from_string(str1):
    
    full_date = [int(x) for x in str1.split('/')]
    return datetime.date(full_date[0], full_date[1], full_date[2])
1112887
protected Temporal parse(String text, Mode mode) {
        if (StringUtils.isBlank(text)) {
            return null;
        }

        // try to parse the date as an ISO8601 date
        if (text.length() >= 16) {
            try {
                return OffsetDateTime.parse(text).toZonedDateTime();
            } catch(Exception e) {}
        }

        // split the text into numerical and text tokens
        Pattern pattern = Pattern.compile("([0-9]+|\\p{L}+)");
        Matcher matcher = pattern.matcher(text);
        List<String> tokens = new ArrayList<>();
        while (matcher.find()) {
            tokens.add(matcher.group(0));
        }

        // get the possibilities for each token
        List<Map<Component, Integer>> tokenPossibilities = new ArrayList<>();
        for (String token : tokens) {
            Map<Component, Integer> possibilities = getTokenPossibilities(token, mode);
            if (possibilities.size() > 0) {
                tokenPossibilities.add(possibilities);
            }
        }

        // see what valid sequences we can make
        List<Component[]> sequences = getPossibleSequences(mode, tokenPossibilities.size(), m_dateStyle);

        outer:
        for (Component[] sequence : sequences) {
            Map<Component, Integer> match = new LinkedHashMap<>();

            for (int c = 0; c < sequence.length; c++) {
                Component component = sequence[c];
                Integer value = tokenPossibilities.get(c).get(component);
                match.put(component, value);

                if (value == null) {
                    continue outer;
                }
            }

            // try to make a valid result from this and return if successful
            Temporal obj = makeResult(match, m_now, m_timezone);
            if (obj != null) {
                return obj;
            }
        }

        return null;
    }
1026100
def _parse_ftp_time(cls, time_text):
        # type: (Text) -> Optional[int]
        
        try:
            tm_year = int(time_text[0:4])
            tm_month = int(time_text[4:6])
            tm_day = int(time_text[6:8])
            tm_hour = int(time_text[8:10])
            tm_min = int(time_text[10:12])
            tm_sec = int(time_text[12:14])
        except ValueError:
            return None
        epoch_time = calendar.timegm(
            (tm_year, tm_month, tm_day, tm_hour, tm_min, tm_sec)
        )
        return epoch_time
634973
def extract_from_text(text):
    
    return tools.remove_duplicates([i[0]
                                    for i in REGEX.findall(text) if i != ''])
349117
def from_string(input_str) -> 'MissionTime':
        # noinspection SpellCheckingInspection
        
        match = RE_INPUT_STRING.match(input_str)
        if not match:
            raise ValueError(f'badly formatted date/time: {input_str}')

        return MissionTime(
            datetime.datetime(
                int(match.group('year')),
                int(match.group('month')),
                int(match.group('day')),
                int(match.group('hour')),
                int(match.group('minute')),
                int(match.group('second')),
            )
        )
930820
def parse_datetime(value):
    """"""

    if isinstance(value, (string_types, text_type, binary_type)):
        value = dateutil.parser.parse(value)
        value.replace(tzinfo=dateutil.tz.tzutc())
        return value
    elif isinstance(value, datetime.datetime):
        value.replace(tzinfo=dateutil.tz.tzutc())
        return value
    elif isinstance(value, datetime.date):
        value = datetime.datetime(value.year, value.month, value.day)
        value.replace(tzinfo=dateutil.tz.tzutc())
        return value
    else:
        raise ValueError('Value must be parsable to datetime object. Got `{}`'.format(type(value)))
968076
def get_datetime(strings: Sequence[str],
                 prefix: str,
                 datetime_format_string: str,
                 ignoreleadingcolon: bool = False,
                 precedingline: str = "") -> Optional[datetime.datetime]:
    
    x = get_string(strings, prefix, ignoreleadingcolon=ignoreleadingcolon,
                   precedingline=precedingline)
    if len(x) == 0:
        return None
    # For the format strings you can pass to datetime.datetime.strptime, see
    # http://docs.python.org/library/datetime.html
    # A typical one is "%d-%b-%Y (%H:%M:%S)"
    d = datetime.datetime.strptime(x, datetime_format_string)
    return d
1144495
def _parse(self, text, mode):
        
        if text is None or not text.strip():
            return None

        # first try to parse as an ISO8601 date, if it doesn't work we'll try other options
        if len(text) >= 16:
            try:
                parsed = iso8601.parse_date(text, default_timezone=None)
                if not parsed.tzinfo:
                    parsed = self._timezone.localize(parsed)

                return parsed
            except iso8601.ParseError:
                pass

        # split the text into numerical and text tokens
        tokens = regex.findall(r'([0-9]+|[^\W\d]+)', text, flags=regex.MULTILINE | regex.UNICODE | regex.V0)

        # get the possibilities for each token
        token_possibilities = []
        for token in tokens:
            possibilities = self._get_token_possibilities(token, mode)
            if len(possibilities) > 0:
                token_possibilities.append(possibilities)

        # see what valid sequences we can make
        sequences = self._get_possible_sequences(mode, len(token_possibilities), self._date_style)

        for sequence in sequences:
            match = OrderedDict()

            for c in range(len(sequence)):
                component = sequence[c]
                value = token_possibilities[c].get(component, None)
                match[component] = value

                if value is None:
                    break
            else:
                # try to make a valid result from this and return if successful
                obj = self._make_result(match, self._now, self._timezone)
                if obj is not None:
                    return obj

        return None
76353
def parse(s):
    """"""
    stopwatch = StopWatch()
    for line in s.splitlines():
      if line.strip():
        parts = line.split(None)
        name = parts[0]
        if name != "%":  # ie not the header line
          rest = (float(v) for v in parts[2:])
          stopwatch.times[parts[0]].merge(Stat.build(*rest))
    return stopwatch
499448
def string2time(text):
    """"""
    length = len(TIME_FORMAT)
    result = None
    while length:
        try:
            result = datetime.strptime(text, TIME_FORMAT[:length])
        except:
            length -= 1
        else:
            break
    return result
356731
def _str_parser(string):
        
        if not any(c.isalpha() for c in string):
            _string = string[:19]
            _length = len(_string)
            if _length > 10:
                return BaseParser.parse_datetime
            elif 6 <= _length <= 10:
                if ':' in _string:
                    return BaseParser.parse_time
                else:
                    return BaseParser.parse_date
            elif _length < 6:
                return BaseParser.parse_time
            else:
                return BaseParser.parse_special
        else:
            return BaseParser.__parse_not_only_str
917826
def stringToDate(fmt="%Y-%m-%d"):
    """"""
    import time
    import datetime
    def conv_func(s):
        return datetime.date(*time.strptime(s,fmt)[:3])
    return conv_func