Parse a ISO 8601 date-time with optional timezone.

    - Return as datetime with timezone adjusted to UTC.
    - Return naive date-time set to UTC.
501309
def parse_and_normalize_url_date(date_str):
    
    if date_str is None:
        return None
    try:
        return d1_common.date_time.dt_from_iso8601_str(date_str)
    except d1_common.date_time.iso8601.ParseError as e:
        raise d1_common.types.exceptions.InvalidRequest(
            0,
            'Invalid date format for URL parameter. date="{}" error="{}"'.format(
                date_str, str(e)
            ),
        )
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
491630
def parse_raw(s, lineno=0):
    
    timestamp_str, timezone_str = s.split(b' ', 1)
    timestamp = float(timestamp_str)
    try:
        timezone = parse_tz(timezone_str)
    except ValueError:
        raise errors.InvalidTimezone(lineno, timezone_str)
    return timestamp, timezone
434004
def iso8601_datetime(s):
    
    try:
        return datetime.datetime.strptime(s, ISO8601_DATETIME_FORMAT).replace(tzinfo=pytz.utc)
    except (TypeError, ValueError):
        return s
1323982
def datetime_from_isoformat(value: str):
    
    if sys.version_info >= (3, 7):
        return datetime.fromisoformat(value)

    return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')
715994
def format_iso_datetime(datetime_obj):
    
    datetime_obj = localize_datetime(datetime_obj, pytz.utc)
    if datetime_obj < MIN_DATE:
        datetime_obj = MIN_DATE
    elif datetime_obj > MAX_DATE:
        datetime_obj = MAX_DATE
    return datetime_obj.replace(tzinfo=None).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
378998
def parse_datetime(dt_str, format):
    """"""
    t = time.strptime(dt_str, format)
    return datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6], pytz.UTC)
705829
def instance(
    dt, tz=UTC  # type: _datetime.datetime  # type: Union[str, _Timezone, None]
):  # type: (...) -> DateTime
    
    if not isinstance(dt, _datetime.datetime):
        raise ValueError("instance() only accepts datetime objects.")

    if isinstance(dt, DateTime):
        return dt

    tz = dt.tzinfo or tz

    # Checking for pytz/tzinfo
    if isinstance(tz, _datetime.tzinfo) and not isinstance(tz, _Timezone):
        # pytz
        if hasattr(tz, "localize") and tz.zone:
            tz = tz.zone
        else:
            # We have no sure way to figure out
            # the timezone name, we fallback
            # on a fixed offset
            tz = tz.utcoffset(dt).total_seconds() / 3600

    return datetime(
        dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, tz=tz
    )
1031074
def from_iso_time(timestring, use_dateutil=True):
    
    if not _iso8601_time_re.match(timestring):
        raise ValueError('Not a valid ISO8601-formatted time string')
    if dateutil_available and use_dateutil:
        return parser.parse(timestring).time()
    else:
        if len(timestring) > 8:  # has microseconds
            fmt = '%H:%M:%S.%f'
        else:
            fmt = '%H:%M:%S'
        return datetime.datetime.strptime(timestring, fmt).time()
59780
def datetimeparse(s):
    
    try:
        dt = dateutil.parser.parse(s)
    except ValueError:
        return None

    return utc_dt(dt)
15606
def parse_time(time_input):
    
    if isinstance(time_input, datetime.date):
        return time_input.isoformat()  # datetime.date only returns date, datetime.datetime also returns time

    if len(time_input) < 8:
        raise ValueError('Invalid time string {}.\n'
                         'Please specify time in formats YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS'.format(time_input))
    time = dateutil.parser.parse(time_input)
    if len(time_input) <= 10:
        return time.date().isoformat()
    return time.isoformat()
351302
def iso8601_format( time )
      value = apply_utc_offset(time)

      str = value.strftime('%Y-%m-%dT%H:%M:%S')
      str << ('.%06d' % value.usec)

      offset = value.gmt_offset.abs
      return str << 'Z' if offset == 0

      offset = sprintf('%02d:%02d', offset / 3600, offset % 3600 / 60)
      return str << (value.gmt_offset < 0 ? '-' : '+') << offset
    end
687911
def parse_date(val, zone='default'):
    val = parse_isodate(val, None)
    '''  '''
    if not val.tzinfo:
        val = timezone[zone].localize(val)
    return val
1311275
def parse_timezone(matches, default_timezone=UTC):
    

    if matches["timezone"] == "Z":
        return UTC
    # This isn't strictly correct, but it's common to encounter dates without
    # timezones so I'll assume the default (which defaults to UTC).
    # Addresses issue 4.
    if matches["timezone"] is None:
        return default_timezone
    sign = matches["tz_sign"]
    hours = to_int(matches, "tz_hour")
    minutes = to_int(matches, "tz_minute", default_to_zero=True)
    description = "%s%02d:%02d" % (sign, hours, minutes)
    if sign == "-":
        hours = -hours
        minutes = -minutes
    return FixedOffset(hours, minutes, description)
1045962
def asdatetime(self, naive=True):
    
    args = list(self.timetuple()[0:6])+[self.microsecond]
    if not naive:
      args.append(self.tzinfo)
    return datetime.datetime(*args)
249412
public T toDateTimeWithTimeZone(String dateTime) {
    return toDateTime(
        ISODateTimeFormat.dateTimeParser().withOffsetParsed().parseDateTime(dateTime));
  }
504326
def _datetime_to_utc(self, dt):
        """"""

        if not dt.tzinfo:
            dt = dt.replace(tzinfo=tz.gettz())
        return dt.astimezone(tz.gettz('UTC'))