Coerce everything to strings.
    All objects representing time get output as ISO8601.
425460
def _default_json_default(obj):
    
    if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):
        return obj.isoformat()
    else:
        return str(obj)
1083006
def _build_str_from_time_items(items):
    
    if not items:
        return None
    items = [int(item) for item in items if item]
    items = items + [0 for _ in xrange(6-len(items))]
    return '%d-%02d-%02d %02d:%02d:%02d' % (items[0], items[1], items[2], items[3], items[4], items[5])
370320
def iso8601timestamp(T=None, nanos=True, utc=False):
	""""""
	T  = time.time() if T is None else T
	Ti = math.floor(T)
	Tn = round((T-Ti)*1e9)
	if Tn >= 1e9:
		Ti += 1
		Tn  = 0
	
	s  = time.gmtime(Ti)      if utc   else time.localtime(Ti)
	f  = time.strftime("%Y%m%dT%H%M%S", s)
	n  = ".{:09d}".format(Tn) if nanos else ""
	tz = "Z"                  if utc   else time.strftime("%z", s)
	return f+n+tz
347918
def _convert_datetime_str(response):
    '''
    
    '''
    if response:
        return dict([(k, '{0}'.format(v)) if isinstance(v, datetime.date) else (k, v) for k, v in six.iteritems(response)])
    return None
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)
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')
139552
def CopyToDateTimeString(self):
    
    if (self._timestamp is None or self._timestamp < self._INT64_MIN or
        self._timestamp > self._INT64_MAX):
      return None

    return super(APFSTime, self)._CopyToDateTimeString()
1217955
def as_iso8601(self, include_millis=False):
        
        date = self.__datetime.strftime("%Y-%m-%d")
        time = self.__datetime.strftime("%H:%M:%S")

        # millis...
        if include_millis:
            micros = float(self.__datetime.strftime("%f"))
            millis = ".%03d" % (micros // 1000)

        else:
            millis = ""

        # time zone...
        zone = self.__datetime.strftime("%z")

        # Z format...
        if float(zone[1:]) == 0.0:
            return "%sT%s%sZ" % (date, time, millis)

        # numeric format...
        zone_hours = zone[:3]
        zone_mins = zone[3:]

        return "%sT%s%s%s:%s" % (date, time, millis, zone_hours, zone_mins)
398547
def _str_to_time(self, str_value):
        """"""
        match = self.rx_time.match(str_value.upper())
        if not match:
            return None
        try:
            gd = match.groupdict()
            hour = int(gd['hour'])
            minute = int(gd['minute'])
            second = int(gd['second'] or 0)
            if gd['tt'] == 'PM':
                hour += 12
            return datetime.time(hour, minute, second)
        except (ValueError, TypeError):
            return None
837911
def to_iso8601_string(self):
        
        string = self._to_string("iso8601")

        if self.tz and self.tz.name == "UTC":
            string = string.replace("+00:00", "Z")

        return string
461570
def iso_time_string(val, show_tzinfo=False):
    
    if not val:
        return ""
    if isinstance(val, six.string_types):
        dt = _parse_datetime_string(val)
    else:
        dt = val
    if not isinstance(dt, datetime.datetime):
        dt = datetime.datetime.fromordinal(dt.toordinal())
    has_tz = (dt.tzinfo is not None)
    if show_tzinfo and has_tz:
        # Need to remove the colon in the TZ portion
        ret = "".join(dt.isoformat().rsplit(":", 1))
    elif show_tzinfo and not has_tz:
        ret = "%s+0000" % dt.isoformat().split(".")[0]
    elif not show_tzinfo and has_tz:
        ret = dt.isoformat()[:-6]
    elif not show_tzinfo and not has_tz:
        ret = dt.isoformat().split(".")[0]
    return ret
399668
def string_to_datetime(self, obj):
        
        if isinstance(obj, six.string_types) and len(obj) == 19:
            try:
                return datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S")
            except ValueError:
                pass
        if isinstance(obj, six.string_types) and len(obj) > 19:
            try:
                return datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S.%f")
            except ValueError:
                pass
        if isinstance(obj, six.string_types) and len(obj) == 10:
            try:
                return datetime.strptime(obj, "%Y-%m-%d")
            except ValueError:
                pass
        return obj
165985
def _datetime_to_iso8601(self, query_dict):
        """"""
        return {
            k: v if not isinstance(v, datetime.datetime) else v.isoformat()
            for k, v in list(query_dict.items())
        }
1039045
def strp_isoformat(strg):
    
    if isinstance(strg, datetime):
        return strg
    if len(strg) < 19 or len(strg) > 26:
        if len(strg) > 30:
            strg = strg[:30] + '...'
        raise ValueError("Invalid ISO formatted time string '%s'"%strg)
    if strg.find(".") == -1:
        strg += '.000000'
    if sys.version[0:3] >= '2.6':
        return datetime.strptime(strg, "%Y-%m-%dT%H:%M:%S.%f")
    else:
        dat, mis = strg.split(".")
        dat = datetime.strptime(dat, "%Y-%m-%dT%H:%M:%S")
        mis = int(float('.' + mis)*1000000)
        return dat.replace(microsecond=mis)
895885
function getIso8601String(timeMs) {
  var time = new Date();
  time.setTime(timeMs);
  return '' +
      time.getUTCFullYear() + '-' +
      leftPadNumber(time.getUTCMonth() + 1, 2, '0') + '-' +
      leftPadNumber(time.getUTCDate(), 2, '0') + 'T' +
      leftPadNumber(time.getUTCHours(), 2, '0') + ':' +
      leftPadNumber(time.getUTCMinutes(), 2, '0') + ':' +
      leftPadNumber(time.getUTCSeconds(), 2, '0') + 'Z';
}
1154057
def clean_up_datetime(obj_map):
    """"""
    clean_map = {}
    for key, value in obj_map.items():
        if isinstance(value, datetime.datetime):
            clean_map[key] = {
                'year': value.year,
                'month': value.month,
                'day': value.day,
                'hour': value.hour,
                'minute': value.minute,
                'second': value.second,
                'microsecond': value.microsecond,
                'tzinfo': value.tzinfo
            }
        elif isinstance(value, dict):
            clean_map[key] = clean_up_datetime(value)
        elif isinstance(value, list):
            if key not in clean_map:
                clean_map[key] = []
            if len(value) > 0:
                for index, list_value in enumerate(value):
                    if isinstance(list_value, dict):
                        clean_map[key].append(clean_up_datetime(list_value))
                    else:
                        clean_map[key].append(list_value)
            else:
                clean_map[key] = value
        else:
            clean_map[key] = value
    return clean_map
18985
def coerce_to_dtype(dtype, value):
    
    name = dtype.name
    if name.startswith('datetime64'):
        if name == 'datetime64[D]':
            return make_datetime64D(value)
        elif name == 'datetime64[ns]':
            return make_datetime64ns(value)
        else:
            raise TypeError(
                "Don't know how to coerce values of dtype %s" % dtype
            )
    return dtype.type(value)