Parses a date from a string based on its length

        :param string:
            A unicode string to parse

        :return:
            A datetime.datetime object, asn1crypto.util.extended_datetime object or
            a unicode string
346045
def _date_by_len(self, string):
        

        strlen = len(string)

        date_format = None
        if strlen == 10:
            date_format = '%Y%m%d%H'
        elif strlen == 12:
            date_format = '%Y%m%d%H%M'
        elif strlen == 14:
            date_format = '%Y%m%d%H%M%S'
        elif strlen == 18:
            date_format = '%Y%m%d%H%M%S.%f'

        if date_format:
            if len(string) >= 4 and string[0:4] == '0000':
                # Year 2000 shares a calendar with year 0, and is supported natively
                t = datetime.strptime('2000' + string[4:], date_format)
                return extended_datetime(
                    0,
                    t.month,
                    t.day,
                    t.hour,
                    t.minute,
                    t.second,
                    t.microsecond,
                    t.tzinfo
                )
            return datetime.strptime(string, date_format)

        return string
1008944
def parse_date(value):
    
    # Do the regex magic; also enforces 2 or 4 digit years
    match = Definitions.DATE_RE.match(value) if value else None
    if not match:
        return None
    # We're going to extract and prepare captured data in 'data'.
    data = {}
    captured = match.groupdict()
    fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
    # If we matched on the RFC 1123 family format
    if captured['year']:
        for field in fields:
            data[field] = captured[field]
    # If we matched on the asctime format, use year2 etc.
    else:
        for field in fields:
            data[field] = captured[field + "2"]
    year = data['year']
    # Interpret lame 2-digit years - base the cutoff on UNIX epoch, in case
    # someone sets a '70' cookie meaning 'distant past'. This won't break for
    # 58 years and people who use 2-digit years are asking for it anyway.
    if len(year) == 2:
        if int(year) < 70:
            year = "20" + year
        else:
            year = "19" + year
    year = int(year)
    # Clamp to [1900, 9999]: strftime has min 1900, datetime has max 9999
    data['year'] = max(1900, min(year, 9999))
    # Other things which are numbers should convert to integer
    for field in ['day', 'hour', 'minute', 'second']:
        if data[field] is None:
            data[field] = 0
        data[field] = int(data[field])
    # Look up the number datetime needs for the named month
    data['month'] = Definitions.month_numbers[data['month'].lower()]
    return datetime.datetime(**data)
1277752
def from_date_time_string(cls, datetime_string, leap_year=False):
        
        dt = datetime.strptime(datetime_string, '%d %b %H:%M')
        return cls(dt.month, dt.day, dt.hour, dt.minute, leap_year)
698787
def parse_string(self, string=''):
        '''
        
        '''
        self.strings = string.splitlines(1)
        self.strings = [self.__parse(line) for line in self.strings]
        return ''.join(self.strings)
1371240
def parse_date(string, formation=None):
        
        if formation:
            _stamp = datetime.datetime.strptime(string, formation).date()
            return _stamp

        _string = string.replace('.', '-').replace('/', '-')
        if '-' in _string:
            if len(_string.split('-')[0]) > 3 or len(_string.split('-')[2]) > 3:
                try:
                    _stamp = datetime.datetime.strptime(_string, '%Y-%m-%d').date()
                except ValueError:
                    try:
                        _stamp = datetime.datetime.strptime(_string, '%m-%d-%Y').date()
                    except ValueError:
                        _stamp = datetime.datetime.strptime(_string, '%d-%m-%Y').date()
            else:
                try:
                    _stamp = datetime.datetime.strptime(_string, '%y-%m-%d').date()
                except ValueError:
                    try:
                        _stamp = datetime.datetime.strptime(_string, '%m-%d-%y').date()
                    except ValueError:
                        _stamp = datetime.datetime.strptime(_string, '%d-%m-%y').date()
        else:
            if len(_string) > 6:
                try:
                    _stamp = datetime.datetime.strptime(_string, '%Y%m%d').date()
                except ValueError:
                    _stamp = datetime.datetime.strptime(_string, '%m%d%Y').date()
            elif len(_string) <= 6:
                try:
                    _stamp = datetime.datetime.strptime(_string, '%y%m%d').date()
                except ValueError:
                    _stamp = datetime.datetime.strptime(_string, '%m%d%y').date()
            else:
                raise CanNotFormatError
        return _stamp
825261
def parse_date_input(value):
    
    try:
        limit = parse_date(value)
    except ValueError:
        limit = None
    if limit is None:
        raise ValueError("'{}' is not a valid date.".format(value))
    limit = datetime(limit.year, limit.month, limit.day)
    if settings.USE_TZ:
        limit = make_aware(limit)
    return limit
1111245
def datetime_from_ISO_string(s):
    
    try:
        return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')
    except ValueError:
        try:
            return datetime.datetime.strptime(s, '%Y-%m-%d')
        except ValueError:
            return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f')
988125
def _parse_date(self, date_string):
        """"""
        date = datetime.strptime(date_string, self._DATE_FORMAT)
        self.date = self._TZ.localize(date).astimezone(pytz.UTC)
373769
function parse(string) {
            var match = isoDateExpression.exec(string);
            if (match) {
                // parse months, days, hours, minutes, seconds, and milliseconds
                // provide default values if necessary
                // parse the UTC offset component
                var year = $Number(match[1]),
                    month = $Number(match[2] || 1) - 1,
                    day = $Number(match[3] || 1) - 1,
                    hour = $Number(match[4] || 0),
                    minute = $Number(match[5] || 0),
                    second = $Number(match[6] || 0),
                    millisecond = Math.floor($Number(match[7] || 0) * 1000),
                    // When time zone is missed, local offset should be used
                    // (ES 5.1 bug)
                    // see https://bugs.ecmascript.org/show_bug.cgi?id=112
                    isLocalTime = Boolean(match[4] && !match[8]),
                    signOffset = match[9] === '-' ? 1 : -1,
                    hourOffset = $Number(match[10] || 0),
                    minuteOffset = $Number(match[11] || 0),
                    result;
                var hasMinutesOrSecondsOrMilliseconds = minute > 0 || second > 0 || millisecond > 0;
                if (
                    hour < (hasMinutesOrSecondsOrMilliseconds ? 24 : 25) &&
                    minute < 60 && second < 60 && millisecond < 1000 &&
                    month > -1 && month < 12 && hourOffset < 24 &&
                    minuteOffset < 60 && // detect invalid offsets
                    day > -1 &&
                    day < (dayFromMonth(year, month + 1) - dayFromMonth(year, month))
                ) {
                    result = (
                        (dayFromMonth(year, month) + day) * 24 +
                        hour +
                        hourOffset * signOffset
                    ) * 60;
                    result = (
                        (result + minute + minuteOffset * signOffset) * 60 +
                        second
                    ) * 1000 + millisecond;
                    if (isLocalTime) {
                        result = toUTC(result);
                    }
                    if (-8.64e15 <= result && result <= 8.64e15) {
                        return result;
                    }
                }
                return NaN;
            }
            return NativeDate.parse.apply(this, arguments);
        }
516003
public static DateTime parseDate(String dateString) {
		dateString = normalize(dateString);
		return parse(dateString, DatePattern.NORM_DATE_FORMAT);
	}
29060
def parse_delta(__string: str) -> datetime.timedelta:
    
    if not __string:
        return datetime.timedelta(0)
    match = re.fullmatch(r"""
        P
        ((?P<days>\d+)D)?
        T?
        ((?P<hours>\d{1,2})H)?
        ((?P<minutes>\d{1,2})M)?
        ((?P<seconds>\d{1,2})?((?:\.(?P<microseconds>\d+))?S)?)
    """, __string, re.VERBOSE)
    if not match:
        raise ValueError('Unable to parse delta {!r}'.format(__string))
    match_dict = {k: int(v) if v else 0 for k, v in match.groupdict().items()}
    return datetime.timedelta(**match_dict)
279203
def string_to_timestamp(timestring):
    

    ts = None

    # Uses an extended version of Go's duration string.
    try:
        delta = durationpy.from_str(timestring);
        past = datetime.datetime.utcnow() - delta
        ts = calendar.timegm(past.timetuple())
        return ts
    except Exception as e:
        pass

    if ts:
        return ts
    # else:
    #     print("Unable to parse timestring.")
    return 0
799388
def parse_date(value):
    
    if not value:
        return None

    if isinstance(value, datetime.date):
        return value

    return parse_datetime(value).date()
779310
def pad_timestamp(string, pad_str=PAD_6_UP):
    

    str_len = len(string)
    pad_len = len(pad_str)

    if str_len < pad_len:
        string = string + pad_str[str_len:]

    return string
1169834
def parse(cls, date_string):
        
        try:
            date = dateparser.parse(date_string)
            if date.tzinfo is None:
                date = dateparser.parse(date_string, tzinfos=cls.tzd)
            return date
        except Exception:
            raise ValueError("Could not parse date string!")
275297
def read_string(cls, string):
        
        if PY3 and not isinstance(string, byte_types):
            string = string.encode()

        return cls.decode(string)
131659
def parse_date(date, default=None):
    
    if date == "":
        if default is not None:
            return default
        else:
            raise Exception("Unknown format for " + date)

    for format_type in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d %H", "%Y-%m-%d", "%d/%m/%Y %H:%M:%S", "%d/%m/%Y %H:%M", "%d/%m/%Y %H",
                        "%d/%m/%Y"]:
        try:
            return datetime.strptime(date, format_type)
        except ValueError:
            pass
    raise Exception("Unknown format for " + date)