Parse a string to produce a :class:`.Date`.

        Accepted formats:
            'YYYY-MM-DD'

        :param s:
        :return:
322666
def parse(cls, s):
        
        try:
            numbers = map(int, s.split("-"))
        except (ValueError, AttributeError):
            raise ValueError("Date string must be in format YYYY-MM-DD")
        else:
            numbers = list(numbers)
            if len(numbers) == 3:
                return cls(*numbers)
            raise ValueError("Date string must be in format YYYY-MM-DD")
455554
def _parse_date(cls, date_str: str) -> Optional[datetime.datetime]:
        """"""
        if not date_str:
            return None

        found_time = False
        found_day = False
        found_month = False
        found_year = False

        hour = minute = second = 0
        day = 0
        month = 0
        year = 0

        for token_match in cls.DATE_TOKENS_RE.finditer(date_str):

            token = token_match.group("token")

            if not found_time:
                time_match = cls.DATE_HMS_TIME_RE.match(token)
                if time_match:
                    found_time = True
                    hour, minute, second = [
                        int(s) for s in time_match.groups()]
                    continue

            if not found_day:
                day_match = cls.DATE_DAY_OF_MONTH_RE.match(token)
                if day_match:
                    found_day = True
                    day = int(day_match.group())
                    continue

            if not found_month:
                month_match = cls.DATE_MONTH_RE.match(token)
                if month_match:
                    found_month = True
                    month = month_match.lastindex
                    continue

            if not found_year:
                year_match = cls.DATE_YEAR_RE.match(token)
                if year_match:
                    found_year = True
                    year = int(year_match.group())

        if 70 <= year <= 99:
            year += 1900
        elif 0 <= year <= 69:
            year += 2000

        if False in (found_day, found_month, found_year, found_time):
            return None

        if not 1 <= day <= 31:
            return None

        if year < 1601 or hour > 23 or minute > 59 or second > 59:
            return None

        return datetime.datetime(year, month, day,
                                 hour, minute, second,
                                 tzinfo=datetime.timezone.utc)
770407
def parsetime(s):
    
    try:
        fields = s.split('.')
        subfields = fields[0].split(':')
        H = int(subfields[0])
        M = int(subfields[1])
        S = int(subfields[2])
        if len(subfields) > 3:
            m = int(subfields[3])
        else:
            m = 0
        if len(fields) > 1:
            m = int(fields[1])
        return (H,M,S,m)
    except:
        raise ValueError("Invalid timestamp, must be in HH:MM:SS.mmm format: " + s)
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!")
311688
def format_date(date):
        
        # Handle time typing
        try:
            date = date.isoformat()
        except AttributeError:  # Not a datetime object
            date = str(date)

        date = parser.parse(date).strftime('%Y-%m-%d')
        return date
943282
def strptime(cls, date_string, format):
        ''
        import _strptime
        return _strptime._strptime_datetime(cls, date_string, format)
1114201
def parse_month_year(date_string):
    
    match = re.match('\d{2}/(?P<month>\d{2})/(?P<year>\d{4})$',
                     date_string.lower())
    if not match:
        raise ValueError("Not format 'dd/mm/yyyy': '{}'".format(date_string))
    month = int(match.group('month'))
    year = int(match.group('year'))
    return month, year
935433
def parse(date)
			return date if date.kind_of?(self)
			r=[]
			dates = date.to_s.chomp.split(/,\s*/)
			dates.each do |d|
				r << d.split(/\s*->\s*/).map {|i| i == ":now" ? :now : i }
			end
			return DateRange.new(r)
		end
107145
def strptime(self, value, format):
        

        value = force_str(value)
        if format == ISO_8601:
            try:
                parsed = parse_datetime(value)
                if not settings.USE_TZ:
                        fr_tz = pytz.timezone(settings.TIME_ZONE)
                        parsed = parsed.astimezone(fr_tz).replace(tzinfo=None)
            except:
                raise APIException(
                    "date parsing error: since parameter use the date format ISO 8601 (ex: 2014-11-18T15:56:58Z)")

            if parsed is None:
                raise APIException(
                    "since parameter use the date format ISO 8601 (ex: 2014-11-18T15:56:58Z)")
            return parsed
        return super(IsoDateTimeField, self).strptime(value, format)
1066585
def from_str(date):
        
        month = date[:3][0] + date[:3][-2:].lower()
        if month not in NAMED_MONTHS:
            raise CanNotFormatError('Month not recognized')

        date = date.replace(',', '').replace(' ', '').replace('.', '')
        try:
            day_unit = [x for x in ['st', 'rd', 'nd', 'th'] if x in date][0]
            day = int(re.search(r'\d+', date.split(day_unit)[0]).group())
            year = int(re.search(r'\d+', date.split(day_unit)[1]).group())
            numeric_month = NAMED_MONTHS[month]
            return datetime.date(int(year), numeric_month, day)
        except:
            raise CanNotFormatError('Not well formatted. Expecting something like May,21st.2015')
692470
def decode_pdf_date(s: str) -> datetime:
    
    if isinstance(s, String):
        s = str(s)
    if s.startswith('D:'):
        s = s[2:]

    # Literal Z00'00', is incorrect but found in the wild,
    # probably made by OS X Quartz -- standardize
    if s.endswith("Z00'00'"):
        s = s.replace("Z00'00'", '+0000')
    elif s.endswith('Z'):
        s = s.replace('Z', '+0000')
    s = s.replace("'", "")  # Remove apos from PDF time strings
    try:
        return datetime.strptime(s, r'%Y%m%d%H%M%S%z')
    except ValueError:
        return datetime.strptime(s, r'%Y%m%d%H%M%S')
1036733
def parse_time(s):
    
    result = None

    if "epoch" in s:
        epoch_time = float(s.rstrip().split(' ')[1][:-1])
        result = datetime.datetime.utcfromtimestamp(epoch_time)
    else:
        _, date_part, time_part = s.split(' ')
        year, mon, day = date_part.split('/')
        hour, minute, sec = time_part.split(':')
        result = datetime.datetime(*map(int, (year, mon, day, hour, minute, sec)))

    return result
289993
def parse_date(s):
    
    if isinstance(s, (datetime.datetime, datetime.date)):
        return s
    try:
        from dateutil.parser import parse
    except ImportError:
        parse = lambda d: datetime.datetime.strptime(d, "%Y-%m-%d")
    return parse(s)
61549
def parse_json_date(value):
    
    if not value:
        return None

    return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC)
1104482
def parse_timestamp(ts_str):
	''''''
	assert isinstance(ts_str, bytes), [type(ts_str), repr(ts_str)]
	ts_str = ts_str.replace('_', ' ')

	# Try to parse time offset in short format
	match = _short_ts_regexp.search(ts_str)
	if match and any(match.groups()):
		delta = list()
		parse_int = lambda v: int(''.join(c for c in v if c.isdigit()))
		for units in [_short_ts_days, _short_ts_s]:
			val = 0
			for k, v in units.iteritems():
				try:
					if not match.group(k): continue
					n = parse_int(match.group(k))
				except IndexError: continue
				val += n * v
			delta.append(val)
		return timezone.localtime(timezone.now()) - timedelta(*delta)

	# Fallback to other generic formats
	ts = None
	if not ts:
		match = re.search( # common BE format
			r'^(?P<date>(?:\d{2}|(?P<Y>\d{4}))-\d{2}-\d{2})'
			r'(?:[ T](?P<time>\d{2}(?::\d{2}(?::\d{2})?)?)?)?$', ts_str )
		if match:
			tpl = 'y' if not match.group('Y') else 'Y'
			tpl, ts_str = '%{}-%m-%d'.format(tpl), match.group('date')
			if match.group('time'):
				tpl_time = ['%H', '%M', '%S']
				ts_str_time = match.group('time').split(':')
				ts_str += ' ' + ':'.join(ts_str_time)
				tpl += ' ' + ':'.join(tpl_time[:len(ts_str_time)])
			try: ts = timezone.make_aware(datetime.strptime(ts_str, tpl))
			except ValueError: pass
	if not ts:
		# coreutils' "date" parses virtually everything, but is more expensive to use
		with open(os.devnull, 'w') as devnull:
			proc = subprocess.Popen(
				['date', '+%s', '-d', ts_str],
				stdout=subprocess.PIPE, stderr=devnull, close_fds=True )
			val = proc.stdout.read()
			if not proc.wait():
				ts = timezone.make_aware(datetime.fromtimestamp(int(val.strip())))

	if ts: return ts
	raise ValueError('Unable to parse date/time string: {0}'.format(ts_str))
1043149
def iso8601_date(s):
    
    try:
        return datetime.datetime.strptime(s, ISO8601_DATE_FORMAT).replace(tzinfo=pytz.utc).date()
    except (TypeError, ValueError):
        return s
314394
def rfc2822_datetime(s):
    
    date_tuple = parsedate(s)
    if date_tuple is None:
        return None
    return datetime.datetime(*date_tuple[:6]).replace(tzinfo=pytz.utc)