Parses an ISO 8601 datetime string and returns a UTC datetime object,
    or the string if parsing failed.
    :param s: ISO 8601-formatted datetime string (2015-01-25T12:34:56Z)
    :return: datetime or str
434004
def iso8601_datetime(s):
    
    try:
        return datetime.datetime.strptime(s, ISO8601_DATETIME_FORMAT).replace(tzinfo=pytz.utc)
    except (TypeError, ValueError):
        return s
1252966
def _parse_date(string: str) -> datetime.date:
    
    return datetime.datetime.strptime(string, '%Y-%m-%d').date()
1023847
public static Date parseFromIso8601(String s) {
        synchronized (MONITOR) {
            try {
                return ISO8601.parse(s);
            } catch (ParseException e) {
                throw new IllegalArgumentException("Unable to parse date", e);
            }
        }
    }
946762
def iso_format_time(time)
      return time unless time.is_a? Time or time.is_a? Date
      time = time.getutc if time.is_a? Time
      time = time.new_offset(0) if time.is_a? DateTime
      time.strftime('%Y-%m-%dT%H:%M:%SZ')
    end
369248
public static Date
parse(String s) throws TextParseException {
	if (s.length() != 14) {
		throw new TextParseException("Invalid time encoding: " + s);
	}

	Calendar c = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
	c.clear();
	try {
		int year = Integer.parseInt(s.substring(0, 4));
		int month = Integer.parseInt(s.substring(4, 6)) - 1;
		int date = Integer.parseInt(s.substring(6, 8));
		int hour = Integer.parseInt(s.substring(8, 10));
		int minute = Integer.parseInt(s.substring(10, 12));
		int second = Integer.parseInt(s.substring(12, 14));
		c.set(year, month, date, hour, minute, second);
	}
	catch (NumberFormatException e) {
		throw new TextParseException("Invalid time encoding: " + s);
	}
	return c.getTime();
}
1243931
def from_iso8601(s):
    
    m = _iso8601_fmt.match(s)
    if not m:
        m = _iso8601_fmt_date.match(s)

    if not m:
        raise ValueError('not a valid iso 8601 format string:[{0}]'.format(s))

    g = m.groupdict()

    def _default_zero(key):
        v = g.get(key, None)
        return int(v) if v else 0

    def _default_none(key):
        v = g.get(key, None)
        return int(v) if v else None

    year = _default_zero('year')
    month = _default_zero('month')
    day = _default_zero('day')
    hour = _default_none('hour')
    minute = _default_none('minute')
    second = _default_none('second')
    microsecond = g.get('microsecond', None)
    if microsecond is not None:
        # append zero when not matching 6 digits
        microsecond = int(microsecond + '0' * (6 - len(microsecond)))
    tz_s = g.get('tz')

    if not (year and month and day):
        raise ValueError('missing y-m-d: [{0}]'.format(s))

    # only date part, time part is none
    if hour == None and minute == None and second == None:
        return datetime.datetime(year, month, day)

    # prepare tz info
    tz = None
    if tz_s:
        if hour is None and minute is None:
            raise ValueError('missing h:m when tzinfo is provided: [{0}]'.format(s))

        negtive = hh = mm = 0

        if tz_s != 'Z':
            negtive = -1 if tz_s[0] == '-' else 1
            hh = int(tz_s[1:3])
            mm = int(tz_s[4:6]) if len(tz_s) > 5 else 0

        tz = FixedTZ(h=hh*negtive, m=mm*negtive)

    return datetime.datetime(
        year=year,
        month=month,
        day=day,
        hour=hour or 0,
        minute=minute or 0,
        second=second or 0,
        microsecond=microsecond or 0,
        tzinfo=tz
    )
234370
def from_iso_datetime(datetimestring, use_dateutil=True):
    
    if not _iso8601_datetime_re.match(datetimestring):
        raise ValueError('Not a valid ISO8601-formatted datetime string')
    # Use dateutil's parser if possible
    if dateutil_available and use_dateutil:
        return parser.isoparse(datetimestring)
    else:
        # Strip off timezone info.
        return datetime.datetime.strptime(datetimestring[:19], '%Y-%m-%dT%H:%M:%S')
1072499
def isostr_to_datetime(dt_str):
    
    if len(dt_str) <= 20:
        return datetime.datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%SZ")
    else:
        dt_str = dt_str.split(".")
        return isostr_to_datetime("%sZ" % dt_str[0])
694976
def as_iso8601(self):
        
        if self.__date is None or self.__time is None:
            return None

        return "20%s-%s-%sT%s:%s:%s0Z" % \
               (self.__date[4:], self.__date[2:4], self.__date[:2], self.__time[:2], self.__time[2:4], self.__time[4:])
1113054
def fromISO(cls, iso_string):

        ''' 
        '''

    # validate input
        title = 'ISO time input for labDT.fromISO'
        isopattern = re.compile('\d{4}-?\d{2}-?\d{2}[\s|T].*')
        if not isopattern.search(iso_string):
            raise ValueError('\n%s is not a valid ISO string.' % title)
        python_datetime = dTparser.parse(iso_string)
        if not python_datetime.tzinfo:
            raise ValueError('\n%s must have timezone info.' % title)

    # construct labDT from parsed string
        dT = python_datetime.astimezone(pytz.utc)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)
1157700
def parse_sws_date(date_string):
    
    if date_string is None:
        return None
    date_formats = ["%m/%d/%Y", "%Y-%m-%d", "%Y%m%d"]
    datetime_obj = None
    for fmt in date_formats:
        try:
            datetime_obj = datetime.strptime(date_string, fmt)
        except ValueError:
            continue
        break
    if datetime_obj is None:
        raise ValueError("Unknown SWS date format")
    return datetime_obj
91973
def parse_ts(ts):
    
    # ISO8601 = '%Y-%m-%dT%H:%M:%SZ'
    # ISO8601_MS = '%Y-%m-%dT%H:%M:%S.%fZ'
    # RFC1123 = '%a, %d %b %Y %H:%M:%S %Z'
    dt = maya.parse(ts.strip())
    return dt.datetime(naive=True)
1067002
def from_ISO_8601(cls, date_string, time_string, tz_string):
        
        # parse tz_string
        if tz_string:
            tz_offset = (int(tz_string[1:3]) * 60) + int(tz_string[3:])
            if tz_string[0] == '-':
                tz_offset = -tz_offset
        else:
            tz_offset = None
        if time_string == '000000':
            # assume no time information
            time_string = ''
            tz_offset = None
        datetime_string = date_string + time_string[:13]
        precision = min((len(datetime_string) - 2) // 2, 7)
        if precision <= 0:
            return None
        fmt = ''.join(('%Y', '%m', '%d', '%H', '%M', '%S', '.%f')[:precision])
        return cls(
            (datetime.strptime(datetime_string, fmt), precision, tz_offset))
677930
public static Date iso8601ToDate(final String dateString) 
        throws ParseException
        {
        final SimpleDateFormat df = 
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        
        // We need to manually parse ISO 8601s ":".
        final String str = StringUtils.substringBeforeLast(dateString, ":") +
            StringUtils.substringAfterLast(dateString, ":");
        return df.parse(str);
        }
1117725
def asDateTime(self):
        
        text = str(self)
        if text.endswith('Z'):
            tzinfo = TimeMixIn.UTC
            text = text[:-1]

        elif '-' in text or '+' in text:
            if '+' in text:
                text, plusminus, tz = string.partition(text, '+')
            else:
                text, plusminus, tz = string.partition(text, '-')

            if self._shortTZ and len(tz) == 2:
                tz += '00'

            if len(tz) != 4:
                raise error.PyAsn1Error('malformed time zone offset %s' % tz)

            try:
                minutes = int(tz[:2]) * 60 + int(tz[2:])
                if plusminus == '-':
                    minutes *= -1

            except ValueError:
                raise error.PyAsn1Error('unknown time specification %s' % self)

            tzinfo = TimeMixIn.FixedOffset(minutes, '?')

        else:
            tzinfo = None

        if '.' in text or ',' in text:
            if '.' in text:
                text, _, ms = string.partition(text, '.')
            else:
                text, _, ms = string.partition(text, ',')

            try:
                ms = int(ms) * 1000

            except ValueError:
                raise error.PyAsn1Error('bad sub-second time specification %s' % self)

        else:
            ms = 0

        if self._optionalMinutes and len(text) - self._yearsDigits == 6:
            text += '0000'
        elif len(text) - self._yearsDigits == 8:
            text += '00'

        try:
            dt = dateandtime.strptime(text, self._yearsDigits == 4 and '%Y%m%d%H%M%S' or '%y%m%d%H%M%S')

        except ValueError:
            raise error.PyAsn1Error('malformed datetime format %s' % self)

        return dt.replace(microsecond=ms, tzinfo=tzinfo)
280367
def parseIBDatetime(s):
    
    if len(s) == 8:
        # YYYYmmdd
        y = int(s[0:4])
        m = int(s[4:6])
        d = int(s[6:8])
        dt = datetime.date(y, m, d)
    elif s.isdigit():
        dt = datetime.datetime.fromtimestamp(
            int(s), datetime.timezone.utc)
    else:
        dt = datetime.datetime.strptime(s, '%Y%m%d  %H:%M:%S')
    return dt
665693
def iso8601_datetime(d):
    
    if d == values.unset:
        return d
    elif isinstance(d, datetime.datetime) or isinstance(d, datetime.date):
        return d.strftime('%Y-%m-%dT%H:%M:%SZ')
    elif isinstance(d, str):
        return d