Parses datetime
    :param v: Input string
    :param default: Default value if exceptions=False
    :param tz: Default pytz timezone or None if utc
    :param exceptions: Raise exception on error or not
    :return: datetime
433877
def parse_datetime(v, default=None, tz=None, exceptions: bool=True) -> datetime:
    
    try:
        t = dateutil_parse(v, default=datetime(2000, 1, 1))
        if tz is None:
            tz = pytz.utc
        return t if t.tzinfo else tz.localize(t)
    except Exception:
        if exceptions:
            raise ValidationError('Failed to parse datetime from "{}"'.format(v))
        return default
142867
def to_datetime_with_default(value, default_value):
        
        result = DateTimeConverter.to_nullable_datetime(value)
        return result if result != None else DateTimeConverter.to_utc_datetime(default_value)
1118422
def timezone(calendar, vtimezones):
    
    for vtimezone in vtimezones:
        remove_x(vtimezone)  # Remove non standard lines from the block
        fake_file = StringIO()
        fake_file.write(str(vtimezone))  # Represent the block as a string
        fake_file.seek(0)
        timezones = tzical(fake_file)  # tzical does not like strings
        # timezones is a tzical object and could contain multiple timezones
        for key in timezones.keys():
            calendar._timezones[key] = timezones.get(key)
462774
def parse_date(record):
	""
	dt = record.pop('datetime')
	fmts = [
		'%Y-%m-%d %H:%M:%S.%f',
		'%Y-%m-%d %H:%M:%S',
	]
	for fmt in fmts:
		try:
			dt = datetime.datetime.strptime(dt, fmt)
			break
		except ValueError:
			pass
	else:
		raise
	tz = pytz.timezone('US/Pacific')
	loc_dt = tz.localize(dt)
	record['datetime'] = loc_dt
	return record
1108714
def get_datetime_type(to_string):
    
    from datetime import datetime

    def datetime_type(string):
        """ Validates UTC datetime. Examples of accepted forms:
        2017-12-31T01:11:59Z,2017-12-31T01:11Z or 2017-12-31T01Z or 2017-12-31 """
        accepted_date_formats = ['%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%MZ',
                                 '%Y-%m-%dT%HZ', '%Y-%m-%d']
        for form in accepted_date_formats:
            try:
                if to_string:
                    return datetime.strptime(string, form).strftime(form)

                return datetime.strptime(string, form)
            except ValueError:
                continue
        raise ValueError("Input '{}' not valid. Valid example: 2000-12-31T12:59:59Z".format(string))

    return datetime_type
352506
def convert_datetime(value, parameter):
    '''
    
    '''
    value = _check_default(value, parameter, ( '', '-', None ))
    if value is None or isinstance(value, datetime.datetime):
        return value
    for fmt in settings.DATETIME_INPUT_FORMATS:
        try:
            return datetime.datetime.strptime(value, fmt)
        except (ValueError, TypeError):
            continue
    raise ValueError("`{}` does not match a format in settings.DATETIME_INPUT_FORMATS".format(value))
1252614
def datetime_timezone(tz):
    
    utc_datetime_naive = datetime.utcnow()
    # return a localized datetime to UTC
    utc_localized_datetime = localize(utc_datetime_naive, 'UTC')
    # normalize the datetime to given timezone
    normalized_datetime = normalize(utc_localized_datetime, tz)
    return normalized_datetime
280232
def date_struct(year, month, day, tz = "UTC"):
    
    ymdtz = (year, month, day, tz)
    if None in ymdtz:
        #logger.debug("a year, month, day or tz value was empty: %s" % str(ymdtz))
        return None # return early if we have a bad value
    try:
        return time.strptime("%s-%s-%s %s" % ymdtz,  "%Y-%m-%d %Z")
    except(TypeError, ValueError):
        #logger.debug("date failed to convert: %s" % str(ymdtz))
        pass
835348
def _process_tz(self, dt, naive, tz):
		""""""
		
		def _tz(t):
			if t in (None, 'naive'):
				return t
			
			if t == 'local':
				if __debug__ and not localtz:
					raise ValueError("Requested conversion to local timezone, but `localtz` not installed.")
				
				t = localtz
			
			if not isinstance(t, tzinfo):
				if __debug__ and not localtz:
					raise ValueError("The `pytz` package must be installed to look up timezone: " + repr(t))
				
				t = get_tz(t)
			
			if not hasattr(t, 'normalize') and get_tz:  # Attempt to handle non-pytz tzinfo.
				t = get_tz(t.tzname(dt))
			
			return t
		
		naive = _tz(naive)
		tz = _tz(tz)
		
		if not dt.tzinfo and naive:
			if hasattr(naive, 'localize'):
				dt = naive.localize(dt)
			else:
				dt = dt.replace(tzinfo=naive)
		
		if not tz:
			return dt
		
		if hasattr(tz, 'normalize'):
			dt = tz.normalize(dt.astimezone(tz))
		elif tz == 'naive':
			dt = dt.replace(tzinfo=None)
		else:
			dt = dt.astimezone(tz)  # Warning: this might not always be entirely correct!
		
		return dt
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
185930
def tgread_date(self):
        
        value = self.read_int()
        if value == 0:
            return None
        else:
            return datetime.fromtimestamp(value, tz=timezone.utc)
1274454
def parse_timestr(timestr):
    
    timedelta_secs = parse_timedelta(timestr)
    sync_start = datetime.now()

    if timedelta_secs:
        target = datetime.now() + timedelta(seconds=timedelta_secs)
    elif timestr.isdigit():
        target = datetime.now() + timedelta(seconds=int(timestr))
    else:
        try:
            target = parse(timestr)
        except:
            # unfortunately, dateutil doesn't raise the best exceptions
            raise ValueError("Unable to parse '{}'".format(timestr))

        # When I do "termdown 10" (the two cases above), I want a
        # countdown for the next 10 seconds. Okay. But when I do
        # "termdown 23:52", I want a countdown that ends at that exact
        # moment -- the countdown is related to real time. Thus, I want
        # my frames to be drawn at full seconds, so I enforce
        # microsecond=0.
        sync_start = sync_start.replace(microsecond=0)
    try:
        # try to convert target to naive local timezone
        target = target.astimezone(tz=tz.tzlocal()).replace(tzinfo=None)
    except ValueError:
        # parse() already returned a naive datetime, all is well
        pass
    return (sync_start, target)
1213200
def adjust_datetime_to_timezone(value, from_tz, to_tz=None):
    
    if to_tz is None:
        to_tz = settings.TIME_ZONE
    if value.tzinfo is None:
        if not hasattr(from_tz, "localize"):
            from_tz = pytz.timezone(smart_str(from_tz))
        value = from_tz.localize(value)
    return value.astimezone(pytz.timezone(smart_str(to_tz)))
15069
def parse_tz(tz):
    
    # from git_repository.py in bzr-git
    sign_byte = tz[0:1]
    # in python 3 b'+006'[0] would return an integer,
    # but b'+006'[0:1] return a new bytes string.
    if sign_byte not in (b'+', b'-'):
        raise ValueError(tz)

    sign = {b'+': +1, b'-': -1}[sign_byte]
    hours = int(tz[1:-2])
    minutes = int(tz[-2:])

    return sign * 60 * (60 * hours + minutes)
1374815
def _convert(value, tzto, defaulttz):
    """"""
    if not isinstance(value, datetime):
        raise ValueError('value must be a datetime.datetime object')

    if value.tzinfo is None:
        value = value.replace(tzinfo=defaulttz)

    return value.astimezone(tzto)
47300
def _normalize_tz(val):
  
  match = _TZ_RE.match(val)
  if match:
    ts, tz = match.groups()
    if len(tz) == 5:
      # If the length of the tz is 5 then it is of the form (+|-)dddd, which is exactly what python
      # wants, so just return it.
      return ts + tz
    if len(tz) == 6:
      # If the length of the tz is 6 then it is of the form (+|-)dd:dd, just remove the colon
      return ts + tz[:3] + tz[4:]
    if tz == "Z" or tz == "z":
      # If the tz is "Z" or 'z', return a timezone of +0000
      return ts + "+0000"
    else:
      # Otherwise, the timzone must be of the format (+|-)dd, in which case we just need to add two
      # "0" to it, and it will be in the proper format.
      return ts + tz + "00"
  else:
    return val
1351459
def datetime_from_ldap(value):
    
    if not value:
        return None
    match = LDAP_DATETIME_RE.match(value)
    if not match:
        return None
    groups = match.groupdict()
    if groups['microsecond']:
        groups['microsecond'] = groups['microsecond'].ljust(6, '0')[:6]
    tzinfo = groups.pop('tzinfo')
    if tzinfo == 'Z':
        tzinfo = timezone.utc
    else:
        offset_mins = int(tzinfo[-2:]) if len(tzinfo) == 5 else 0
        offset = 60 * int(tzinfo[1:3]) + offset_mins
        if tzinfo[0] == '-':
            offset = - offset
        tzinfo = timezone.get_fixed_timezone(offset)
    kwargs = {k: int(v) for k, v in groups.items() if v is not None}
    kwargs['tzinfo'] = tzinfo
    return datetime.datetime(**kwargs)