Return a timedelta object based on the value which can be a timedelta
    or a number of seconds (int or float).
    Raise an exception in all other cases.
18710
def get_delta(value):
    
    if isinstance(value, (int, float)):
        return timedelta(seconds=value)
    elif isinstance(value, timedelta):
        return value
    raise Exception('Invalid delta')
1037694
def wait_time(self, value):
        

        if value is not None:
            assert type(value) in (int, float), "'{0}' attribute: '{1}' type is not 'int' or 'float'!".format(
                "wait_time", value)
            assert value >= 0, "'{0}' attribute: '{1}' need to be positive!".format("wait_time", value)
        self.__wait_time = value
866446
def python_value(self, value):
        
        value = super(PendulumDateTimeField, self).python_value(value)

        if isinstance(value, datetime.datetime):
            value = pendulum.instance(value)
        elif isinstance(value, datetime.date):
            value = pendulum.instance(
                datetime.datetime.combine(
                    value, datetime.datetime.min.time()
                )
            )
        elif isinstance(value, string_types):
            value = pendulum.parse(value)

        return value
787545
def time_from_number(self, value):
        
        if not isinstance(value, numbers.Real):
            return None
        delta = datetime.timedelta(days=value)
        minutes, second = divmod(delta.seconds, 60)
        hour, minute = divmod(minutes, 60)
        return datetime.time(hour, minute, second)
18711
def get_datetime(timestamp):
    
    timestamp_is_float = False
    try:
        float(timestamp)
        timestamp_is_float = True
    except (ValueError, TypeError):
        pass

    if timestamp_is_float == True:
        raise ValueError("Timestamp %s is a float"%(timestamp,))

    #First try to use date util. Failing that, continue
    try:
        parsed_dt = parse(timestamp, dayfirst=False)
        if parsed_dt.tzinfo is None:
            return parsed_dt
        else:

            return parsed_dt.replace(tzinfo=None)
    except:
        pass

    if isinstance(timestamp, datetime):
        return timestamp

    fmt = guess_timefmt(timestamp)
    if fmt is None:
        fmt = FORMAT

    # and proceed as usual
    try:
        ts_time = datetime.strptime(timestamp, fmt)
    except ValueError as e:
        if e.message.split(' ', 1)[0].strip() == 'unconverted':
            utcoffset = e.message.split()[3].strip()
            timestamp = timestamp.replace(utcoffset, '')
            ts_time = datetime.strptime(timestamp, fmt)
            # Apply offset
            tzoffset = timedelta(hours=int(utcoffset[0:3]),
                                          minutes=int(utcoffset[3:5]))
            ts_time -= tzoffset
        else:
            raise e

    return ts_time
1095971
def timedelta_to_httpdate(td):
    
    if isinstance(td, (int, float)):
        return format_date_time(time.time() + td)
    elif isinstance(td, timedelta):
        return format_date_time(time.time() + total_seconds(td))
    else:
        raise TypeError("expected datetime.timedelta or number of seconds"
                        "(int/float), got '%s'" % td)
1366987
def from_timedelta(cls, timedelta):
        """"""
        from math import ceil
        units = ceil(timedelta.total_seconds() / cls.time_unit)
        return cls.create(units)
553490
def timedelta_div(first: datetime.timedelta,
                  second: datetime.timedelta) -> Optional[float]:
    
    first_seconds = timedelta_seconds(first)
    second_seconds = timedelta_seconds(second)

    if not second_seconds:
        return None

    return first_seconds / second_seconds
547834
def to_timestamp(self, value):
        
        if isinstance(value, (six.integer_types, float, six.string_types)):
            try:
                return float(value)
            except ValueError:
                value = self.datetime_str_to_datetime(value)

        if isinstance(value, datetime.datetime):
            return self._datetime_to_timestamp(value)

        if value is None:
            try:
                return float(self.default)
            except:
                return 0.0

        raise exceptions.ValidationError(
            "Unable to convert value: '%s' to timestamp" % value,
            code="invalid_timestamp"
        )
1198042
def _seconds_to_days(cls, val, **kwargs):
        '''
        
        '''
        zero_value = kwargs.get('zero_value', 0)
        if val is not None:
            if val == zero_value:
                return 0
            return val / 86400
        else:
            return 'Not Defined'
907868
def _add_timedeltalike_scalar(self, other):
        
        if isna(other):
            # i.e np.timedelta64("NaT"), not recognized by delta_to_nanoseconds
            new_values = np.empty(len(self), dtype='i8')
            new_values[:] = iNaT
            return new_values

        inc = delta_to_nanoseconds(other)
        new_values = checked_add_with_arr(self.asi8, inc,
                                          arr_mask=self._isnan).view('i8')
        new_values = self._maybe_mask_results(new_values)
        return new_values.view('i8')
1089464
def get_timerange(self, start, end, code=None):
        
        try:
            return self.data.loc[(slice(pd.Timestamp(start), pd.Timestamp(end)), slice(code)), :]
        except:
            return ValueError('CANNOT FOUND THIS TIME RANGE')
321591
def _postprocess(valuestr):
    
    # USGS has started quoting time sometimes.  Grr, strip quotes in this case
    intpattern = re.compile(r'^\-?\d+$')
    floatpattern = re.compile(r'^\-?\d+\.\d+(E[+-]?\d\d+)?$')
    datedtpattern = '%Y-%m-%d'
    datedttimepattern = '%Y-%m-%dT%H:%M:%SZ'
    timedtpattern = '%H:%M:%S.%f'
    timepattern = re.compile(r'^\d{2}:\d{2}:\d{2}(\.\d{6})?')
    if valuestr.startswith('"') and valuestr.endswith('"'):
        # it's a string
        return valuestr[1:-1]
    elif re.match(intpattern, valuestr):
        # it's an integer
        return int(valuestr)
    elif re.match(floatpattern, valuestr):
        # floating point number
        return float(valuestr)
    # now let's try the datetime objects; throws exception if it doesn't match
    try:
        return datetime.datetime.strptime(valuestr, datedtpattern).date()
    except ValueError:
        pass
    try:
        return datetime.datetime.strptime(valuestr, datedttimepattern)
    except ValueError:
        pass
    # time parsing is complicated: Python's datetime module only accepts
    # fractions of a second only up to 6 digits
    mat = re.match(timepattern, valuestr)
    if mat:
        test = mat.group(0)
        try:
            return datetime.datetime.strptime(test, timedtpattern).time()
        except ValueError:
            pass

    # If we get here, we still haven't returned anything.
    logging.info(
        "The value %s couldn't be parsed as " % valuestr
        + "int, float, date, time, datetime. Returning it as string.")
    return valuestr
1016617
def set_time_rate(self, value):
        '''
        
        '''
        if isinstance(value, float) is False:
            raise TypeError("The type of __time_rate must be float.")

        if value <= 0.0:
            raise ValueError("The value of __time_rate must be greater than 0.0")

        self.__time_rate = value
1329466
def memorized_timedelta(seconds):
    ''''''
    try:
        return _timedelta_cache[seconds]
    except KeyError:
        delta = timedelta(seconds=seconds)
        _timedelta_cache[seconds] = delta
        return delta
757693
def get_duration(self, seconds=False):
        
        if seconds:
            return str(self.duration)
        delta = datetime.timedelta(seconds=self.duration)
        return str(delta)
301123
def convert_timedelta_type(obj):
    ''' 

    '''
    if isinstance(obj, dt.timedelta):
        return obj.total_seconds() * 1000.
    elif isinstance(obj, np.timedelta64):
        return (obj / NP_MS_DELTA)