Convert struct_time tuples with possibly invalid values to valid
    ones by substituting the closest valid value.
175018
def sanitizeStructTime(struct):
    
    maxValues = (9999, 12, 31, 23, 59, 59)
    minValues = (1, 1, 1, 0, 0, 0)
    newstruct = []
    for value, maxValue, minValue in zip(struct[:6], maxValues, minValues):
        newstruct.append(max(minValue, min(value, maxValue)))
    return tuple(newstruct) + struct[6:]
412867
def to_tuple(value, strict=True, force_int=True):
    
    if isinstance(value, int):
        seconds = value
        minutes, seconds = divmod(seconds, 60)
        hours, minutes = divmod(minutes, 60)
    elif isinstance(value, str):
        hours, minutes, seconds = _fix_tuple(
            _parse(value, strict)
        )
    elif isinstance(value, tuple):
        check_tuple(value, strict)
        hours, minutes, seconds = _fix_tuple(value)
    elif isinstance(value, timedelta):
        seconds = value.total_seconds()
        if force_int:
            seconds = int(round(seconds))
        minutes, seconds = divmod(seconds, 60)
        hours, minutes = divmod(minutes, 60)

    return (hours, minutes, seconds,)
547967
def _validate_prepare_time(self, t, pos_c):
        
        if hasattr(t, 'unit'):
            t = t.decompose(self.units).value

        if not isiterable(t):
            t = np.atleast_1d(t)

        t = np.ascontiguousarray(t.ravel())

        if len(t) > 1:
            if len(t) != pos_c.shape[0]:
                raise ValueError("If passing in an array of times, it must have a shape "
                                 "compatible with the input position(s).")

        return t
302561
def dehydrate_time(value):
    
    if isinstance(value, Time):
        nanoseconds = int(value.ticks * 1000000000)
    elif isinstance(value, time):
        nanoseconds = (3600000000000 * value.hour + 60000000000 * value.minute +
                       1000000000 * value.second + 1000 * value.microsecond)
    else:
        raise TypeError("Value must be a neotime.Time or a datetime.time")
    if value.tzinfo:
        return Structure(b"T", nanoseconds, value.tzinfo.utcoffset(value).seconds)
    else:
        return Structure(b"t", nanoseconds)
1296143
def check_time(value):
    """"""
    if value is None:
        return None
    if isinstance(value, (time.struct_time, tuple)):
        return value
    if isinstance(value, datetime.datetime):
        return value.timetuple()
    if isinstance(value, datetime.date):
        res = datetime.datetime.utcnow()
        res.replace(year=value.year, month=value.month, day=value.day)
        return res.timetuple()
    if isinstance(value, datetime.time):
        return datetime.datetime.combine(datetime.date.today(),
                                         value).timetuple()
    if isinteger(value):
        # Handle integer as timestamp
        return time.gmtime(value)
    if isinstance(value, basestring):
        if value.lower() == 'now':
            return time.gmtime()
        # TODO: parsinng some popular strings
    raise ValueError("Unsupported time representation:" + repr(value))
1254793
def cast_datetime_filter(value):
    
    if isinstance(value, str):
        dtime = parse_datetime(value)

    elif isinstance(value, datetime):
        dtime = value
    else:
        raise ValueError('Received value of type {0}'.format(type(value)))

    return dtime.isoformat()
554596
def normalize_time(timestamp):
    """"""
    offset = timestamp.utcoffset()
    if offset is None:
        return timestamp
    return timestamp.replace(tzinfo=None) - offset
1157996
def _NormalizeTime(self, time):
    """"""
    if isinstance(time, rdfvalue.RDFDatetime):
      return time.AsMicrosecondsSinceEpoch()
    if isinstance(time, rdfvalue.Duration):
      return time.microseconds
    return int(time)
896989
def validate_time(self, duration=False):
        
        super(TimeFilter, self).validate()
        timestamp = now = time.time()

        if str(self._value).isdigit():
            # Literal UNIX timestamp
            try:
                timestamp = float(self._value)
            except (ValueError, TypeError), exc:
                raise FilterError("Bad timestamp value %r in %r (%s)" % (self._value, self._condition, exc))
        else:
            # Something human readable
            delta = self.TIMEDELTA_RE.match(self._value)
            ##print self.TIMEDELTA_RE.pattern
            if delta:
                # Time delta
                for unit, val in delta.groupdict().items():
                    if val:
                        timestamp = self.TIMEDELTA_UNITS[unit](timestamp, int(val, 10))

                if duration:
                    timestamp = now - timestamp
                else:
                    # Invert logic for time deltas (+ = older; - = within the delta range)
                    if self._cmp == operator.lt:
                        self._cmp = operator.gt
                        self._rt_cmp = 'greater'
                    elif self._cmp == operator.gt:
                        self._cmp = operator.lt
                        self._rt_cmp = 'less'
            else:
                # Assume it's an absolute date
                if '/' in self._value:
                    # U.S.
                    dtfmt = "%m/%d/%Y"
                elif '.' in self._value:
                    # European
                    dtfmt = "%d.%m.%Y"
                else:
                    # Fall back to ISO
                    dtfmt = "%Y-%m-%d"

                val = str(self._value).upper().replace(' ', 'T')
                if 'T' in val:
                    # Time also given
                    dtfmt += "T%H:%M:%S"[:3+3*val.count(':')]

                try:
                    timestamp = time.mktime(time.strptime(val, dtfmt))
                except (ValueError), exc:
                    raise FilterError("Bad timestamp value %r in %r (%s)" % (self._value, self._condition, exc))

                if duration:
                    timestamp -= now

        self._value = timestamp
1006810
def process_formdata(self, valuelist):
        """"""
        if valuelist:
            time_str = u' '.join(valuelist)
            try:
                timetuple = time.strptime(time_str, self.format)
                self.data = datetime.time(*timetuple[3:6])
            except ValueError:
                self.data = None
                raise
1069388
def writeICCdatetime(t=None):
    

    import time
    if t is None:
        t = time.gmtime()
    return struct.pack('>6H', *t[:6])
1326992
def _reduce_datetimes(row):
    """"""

    row = list(row)

    for i in range(len(row)):
        if hasattr(row[i], 'isoformat'):
            row[i] = row[i].isoformat()
    return tuple(row)
115087
def _prune_invalid_time_reductions(spec):
    """"""
    valid_reductions = []
    if not spec['var'].def_time and spec['dtype_out_time'] is not None:
        for reduction in spec['dtype_out_time']:
            if reduction not in _TIME_DEFINED_REDUCTIONS:
                valid_reductions.append(reduction)
            else:
                msg = ("Var {0} has no time dimension "
                       "for the given time reduction "
                       "{1} so this calculation will "
                       "be skipped".format(spec['var'].name, reduction))
                logging.info(msg)
    else:
        valid_reductions = spec['dtype_out_time']
    return valid_reductions
86818
def to_simple(self, value, **options):  # nolint
        "  "

        # (string, unicode)
        if isinstance(value, basestring):
            return smart_unicode(value)

        # (int, long, float, real, complex, decimal)
        if isinstance(value, Number):
            return float(str(value)) if isinstance(value, Decimal) else value

        # (datetime, data, time)
        if isinstance(value, (datetime, date, time)):
            return self.to_simple_datetime(value)

        # (dict, ordereddict, mutable mapping)
        if isinstance(value, collections.MutableMapping):
            return dict(
                (k, self.to_simple(v, **options)) for k, v in value.items())

        # (tuple, list, set, iterators)
        if isinstance(value, collections.Iterable):
            return [self.to_simple(o, **options) for o in value]

        # (None, True, False)
        if value is None or value is True or value is False:
            return value

        if hasattr(value, 'to_simple') and not inspect.isclass(value):
            return self.to_simple(value.to_simple(self), **options)

        if isinstance(value, Model):
            return self.to_simple_model(value, **options)

        return str(value)
886016
def _process_out_of_bounds(self, value, start, end):
        ""
        if isinstance(value, np.datetime64):
            v = dt64_to_dt(value)
            if isinstance(start, (int, float)):
                start = convert_timestamp(start)
            if isinstance(end, (int, float)):
                end = convert_timestamp(end)
            s, e = start, end
            if isinstance(s, np.datetime64):
                s = dt64_to_dt(s)
            if isinstance(e, np.datetime64):
                e = dt64_to_dt(e)
        else:
            v, s, e = value, start, end

        if v < s:
            value = start
        elif v > e:
            value = end

        return value
1187052
private Tuple2<Object, T> mapPkToRow(String timestamp, JSONObject jsonRow, List<String> joinFields) {
        Object joinValue = null;
        T rowValues = null;
        try {
            rowValues = rowMapper.newInstance();
            rowValues.getClass().getMethod("setTimestamp", String.class).invoke(rowValues, timestamp);
            for (Object key : jsonRow.keySet()) {
                String colValue = key.toString();
                Util.applyKVToBean(rowValues, colValue, jsonRow.get(colValue));
                if (joinFields.contains(colValue)) {
                    joinValue = (joinValue == null)?jsonRow.get(colValue):(joinValue + "\u0001" + jsonRow.get(colValue));
                }
            }
            if (joinFields.contains("timestamp")) {// Join field could contain timestamp(timestamp can be out of the actual data JSON, so we try this way)
                joinValue = (joinValue == null)?timestamp:(joinValue + "\u0001" + timestamp);
            }
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) {
            Logger.getLogger(Joiner4Bean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return new Tuple2<>(joinValue, rowValues);
    }
1268854
def _cimdatetime_representer(dumper, cimdatetime):
    
    cimdatetime_str = str(cimdatetime)
    node = dumper.represent_scalar(CIMDATETIME_TAG, cimdatetime_str)
    return node