Python datetime.timedelta.total_seconds() Examples

The following are 18 code examples of datetime.timedelta.total_seconds(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module datetime.timedelta , or try the search function .
Example #1
Source File: http.py    From lambda-packs with MIT License 6 votes vote down vote up
def dump_age(age=None):
    """Formats the duration as a base-10 integer.

    :param age: should be an integer number of seconds,
                a :class:`datetime.timedelta` object, or,
                if the age is unknown, `None` (default).
    """
    if age is None:
        return
    if isinstance(age, timedelta):
        # do the equivalent of Python 2.7's timedelta.total_seconds(),
        # but disregarding fractional seconds
        age = age.seconds + (age.days * 24 * 3600)

    age = int(age)
    if age < 0:
        raise ValueError('age cannot be negative')

    return str(age) 
Example #2
Source File: http.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 6 votes vote down vote up
def dump_age(age=None):
    """Formats the duration as a base-10 integer.

    :param age: should be an integer number of seconds,
                a :class:`datetime.timedelta` object, or,
                if the age is unknown, `None` (default).
    """
    if age is None:
        return
    if isinstance(age, timedelta):
        # do the equivalent of Python 2.7's timedelta.total_seconds(),
        # but disregarding fractional seconds
        age = age.seconds + (age.days * 24 * 3600)

    age = int(age)
    if age < 0:
        raise ValueError('age cannot be negative')

    return str(age) 
Example #3
Source File: http.py    From android_universal with MIT License 6 votes vote down vote up
def dump_age(age=None):
    """Formats the duration as a base-10 integer.

    :param age: should be an integer number of seconds,
                a :class:`datetime.timedelta` object, or,
                if the age is unknown, `None` (default).
    """
    if age is None:
        return
    if isinstance(age, timedelta):
        # do the equivalent of Python 2.7's timedelta.total_seconds(),
        # but disregarding fractional seconds
        age = age.seconds + (age.days * 24 * 3600)

    age = int(age)
    if age < 0:
        raise ValueError('age cannot be negative')

    return str(age) 
Example #4
Source File: http.py    From planespotter with MIT License 6 votes vote down vote up
def dump_age(age=None):
    """Formats the duration as a base-10 integer.

    :param age: should be an integer number of seconds,
                a :class:`datetime.timedelta` object, or,
                if the age is unknown, `None` (default).
    """
    if age is None:
        return
    if isinstance(age, timedelta):
        # do the equivalent of Python 2.7's timedelta.total_seconds(),
        # but disregarding fractional seconds
        age = age.seconds + (age.days * 24 * 3600)

    age = int(age)
    if age < 0:
        raise ValueError('age cannot be negative')

    return str(age) 
Example #5
Source File: views.py    From healthchecks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def bounce(request, code):
    notification = get_object_or_404(Notification, code=code)

    # If webhook is more than 10 minutes late, don't accept it:
    td = timezone.now() - notification.created
    if td.total_seconds() > 600:
        return HttpResponseForbidden()

    notification.error = request.body.decode()[:200]
    notification.save()

    notification.channel.last_error = notification.error
    if request.GET.get("type") in (None, "Permanent"):
        # For permanent bounces, mark the channel as not verified, so we
        # will not try to deliver to it again.
        notification.channel.email_verified = False

    notification.channel.save()

    return HttpResponse() 
Example #6
Source File: http.py    From scylla with Apache License 2.0 6 votes vote down vote up
def dump_age(age=None):
    """Formats the duration as a base-10 integer.

    :param age: should be an integer number of seconds,
                a :class:`datetime.timedelta` object, or,
                if the age is unknown, `None` (default).
    """
    if age is None:
        return
    if isinstance(age, timedelta):
        # do the equivalent of Python 2.7's timedelta.total_seconds(),
        # but disregarding fractional seconds
        age = age.seconds + (age.days * 24 * 3600)

    age = int(age)
    if age < 0:
        raise ValueError("age cannot be negative")

    return str(age) 
Example #7
Source File: http.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
def dump_age(age=None):
    """Formats the duration as a base-10 integer.

    :param age: should be an integer number of seconds,
                a :class:`datetime.timedelta` object, or,
                if the age is unknown, `None` (default).
    """
    if age is None:
        return
    if isinstance(age, timedelta):
        # do the equivalent of Python 2.7's timedelta.total_seconds(),
        # but disregarding fractional seconds
        age = age.seconds + (age.days * 24 * 3600)

    age = int(age)
    if age < 0:
        raise ValueError("age cannot be negative")

    return str(age) 
Example #8
Source File: http.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
def dump_age(age=None):
    """Formats the duration as a base-10 integer.

    :param age: should be an integer number of seconds,
                a :class:`datetime.timedelta` object, or,
                if the age is unknown, `None` (default).
    """
    if age is None:
        return
    if isinstance(age, timedelta):
        # do the equivalent of Python 2.7's timedelta.total_seconds(),
        # but disregarding fractional seconds
        age = age.seconds + (age.days * 24 * 3600)

    age = int(age)
    if age < 0:
        raise ValueError("age cannot be negative")

    return str(age) 
Example #9
Source File: __init__.py    From OpenMTC with Eclipse Public License 1.0 6 votes vote down vote up
def _check_timetable(self):
        if not self._running:
            return

        now = datetime_now()
        sleeptime = self.timeout

        while len(self._timetable) > 0 and now >= self._timetable[0][0]:
            expired_path = self._timetable.pop(0)[1]
            # self._resources.pop(expired_path)
            self.logger.info("Resource has expired: %s", expired_path)
            self._purge(expired_path)
        try:
            td = self._timetable[0][0] - now
            try:
                td = td.total_seconds()
            except AttributeError:
                # Jython does not have timedelta.total_seconds()
                td = td.seconds + (td.days * 24 * 60 * 60)
            sleeptime = min(td, sleeptime)
        except IndexError:
            pass

        self._timer = self.api.set_timer(sleeptime, self._check_timetable) 
Example #10
Source File: http.py    From recruit with Apache License 2.0 6 votes vote down vote up
def dump_age(age=None):
    """Formats the duration as a base-10 integer.

    :param age: should be an integer number of seconds,
                a :class:`datetime.timedelta` object, or,
                if the age is unknown, `None` (default).
    """
    if age is None:
        return
    if isinstance(age, timedelta):
        # do the equivalent of Python 2.7's timedelta.total_seconds(),
        # but disregarding fractional seconds
        age = age.seconds + (age.days * 24 * 3600)

    age = int(age)
    if age < 0:
        raise ValueError("age cannot be negative")

    return str(age) 
Example #11
Source File: plugin.py    From SmartVirtualThermostat with MIT License 5 votes vote down vote up
def AutoCallib(self):

        now = datetime.now()
        if self.Internals['ALStatus'] != 1:  # not initalized... do nothing
            Domoticz.Debug("Fist pass at AutoCallib... no callibration")
            pass
        elif self.Internals['LastPwr'] == 0:  # heater was off last time, do nothing
            Domoticz.Debug("Last power was zero... no callibration")
            pass
        elif self.Internals['LastPwr'] == 100 and self.intemp < self.Internals['LastSetPoint']:
            # heater was on max but setpoint was not reached... no learning
            Domoticz.Debug("Last power was 100% but setpoint not reached... no callibration")
            pass
        elif self.intemp > self.Internals['LastInT'] and self.Internals['LastSetPoint'] > self.Internals['LastInT']:
            # learning ConstC
            ConstC = (self.Internals['ConstC'] * ((self.Internals['LastSetPoint'] - self.Internals['LastInT']) /
                                                  (self.intemp - self.Internals['LastInT']) *
                                                  (timedelta.total_seconds(now - self.lastcalc) /
                                                   (self.calculate_period * 60))))
            self.WriteLog("New calc for ConstC = {}".format(ConstC), "Verbose")
            self.Internals['ConstC'] = round((self.Internals['ConstC'] * self.Internals['nbCC'] + ConstC) /
                                             (self.Internals['nbCC'] + 1), 1)
            self.Internals['nbCC'] = min(self.Internals['nbCC'] + 1, 50)
            self.WriteLog("ConstC updated to {}".format(self.Internals['ConstC']), "Verbose")
        elif (self.outtemp is not None and self.Internals['LastOutT'] is not None) and \
                 self.Internals['LastSetPoint'] > self.Internals['LastOutT']:
            # learning ConstT
            ConstT = (self.Internals['ConstT'] + ((self.Internals['LastSetPoint'] - self.intemp) /
                                                  (self.Internals['LastSetPoint'] - self.Internals['LastOutT']) *
                                                  self.Internals['ConstC'] *
                                                  (timedelta.total_seconds(now - self.lastcalc) /
                                                   (self.calculate_period * 60))))
            self.WriteLog("New calc for ConstT = {}".format(ConstT), "Verbose")
            self.Internals['ConstT'] = round((self.Internals['ConstT'] * self.Internals['nbCT'] + ConstT) /
                                             (self.Internals['nbCT'] + 1), 1)
            self.Internals['nbCT'] = min(self.Internals['nbCT'] + 1, 50)
            self.WriteLog("ConstT updated to {}".format(self.Internals['ConstT']), "Verbose") 
Example #12
Source File: views.py    From healthchecks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pings(request, code):
    check = get_object_or_404(Check, code=code)
    if check.project_id != request.project.id:
        return HttpResponseForbidden()

    # Look up ping log limit from account's profile.
    # There might be more pings in the database (depends on how pruning is handled)
    # but we will not return more than the limit allows.
    profile = Profile.objects.get(user__project=request.project)
    limit = profile.ping_log_limit

    # Query in descending order so we're sure to get the most recent
    # pings, regardless of the limit restriction
    pings = Ping.objects.filter(owner=check).order_by("-id")[:limit]

    # Ascending order is more convenient for calculating duration, so use reverse()
    prev, dicts = None, []
    for ping in reversed(pings):
        d = ping.to_dict()
        if ping.kind != "start" and prev and prev.kind == "start":
            delta = ping.created - prev.created
            if delta < MAX_DELTA:
                d["duration"] = delta.total_seconds()

        dicts.insert(0, d)
        prev = ping

    return JsonResponse({"pings": dicts}) 
Example #13
Source File: test_max_age.py    From sanic-cors with MIT License 5 votes vote down vote up
def test_time_delta(self):
        ''' If the methods parameter is defined, always return the allowed
            methods defined by the user.
        '''
        # timedelta.total_seconds is not available in older versions of Python
        if sys.version_info < (2, 7):
            return

        resp = self.preflight('/test_time_delta', origin='www.example.com')
        self.assertEqual(resp.headers.get(ACL_MAX_AGE), '600') 
Example #14
Source File: perfutils.py    From openmaptiles-tools with MIT License 5 votes vote down vote up
def __post_init__(self):
        self.tile_avg_size = float(self.bytes) / self.tiles if self.tiles else 0
        if self.duration:
            self.gen_speed = float(self.tiles) / self.duration.total_seconds() 
Example #15
Source File: transaction.py    From btcpy with GNU Lesser General Public License v3.0 5 votes vote down vote up
def from_timedelta(cls, timedelta):
        """expects a datetime.timedelta object"""
        from math import ceil
        units = ceil(timedelta.total_seconds() / cls.time_unit)
        return cls.create(units) 
Example #16
Source File: _sync.py    From backoff with MIT License 4 votes vote down vote up
def retry_predicate(target, wait_gen, predicate,
                    max_tries, max_time, jitter,
                    on_success, on_backoff, on_giveup,
                    wait_gen_kwargs):

    @functools.wraps(target)
    def retry(*args, **kwargs):

        # change names because python 2.x doesn't have nonlocal
        max_tries_ = _maybe_call(max_tries)
        max_time_ = _maybe_call(max_time)

        tries = 0
        start = datetime.datetime.now()
        wait = _init_wait_gen(wait_gen, wait_gen_kwargs)
        while True:
            tries += 1
            elapsed = timedelta.total_seconds(datetime.datetime.now() - start)
            details = (target, args, kwargs, tries, elapsed)

            ret = target(*args, **kwargs)
            if predicate(ret):
                max_tries_exceeded = (tries == max_tries_)
                max_time_exceeded = (max_time_ is not None and
                                     elapsed >= max_time_)

                if max_tries_exceeded or max_time_exceeded:
                    _call_handlers(on_giveup, *details, value=ret)
                    break

                try:
                    seconds = _next_wait(wait, jitter, elapsed, max_time_)
                except StopIteration:
                    _call_handlers(on_giveup, *details)
                    break

                _call_handlers(on_backoff, *details,
                               value=ret, wait=seconds)

                time.sleep(seconds)
                continue
            else:
                _call_handlers(on_success, *details, value=ret)
                break

        return ret

    return retry 
Example #17
Source File: _sync.py    From backoff with MIT License 4 votes vote down vote up
def retry_exception(target, wait_gen, exception,
                    max_tries, max_time, jitter, giveup,
                    on_success, on_backoff, on_giveup,
                    wait_gen_kwargs):

    @functools.wraps(target)
    def retry(*args, **kwargs):

        # change names because python 2.x doesn't have nonlocal
        max_tries_ = _maybe_call(max_tries)
        max_time_ = _maybe_call(max_time)

        tries = 0
        start = datetime.datetime.now()
        wait = _init_wait_gen(wait_gen, wait_gen_kwargs)
        while True:
            tries += 1
            elapsed = timedelta.total_seconds(datetime.datetime.now() - start)
            details = (target, args, kwargs, tries, elapsed)

            try:
                ret = target(*args, **kwargs)
            except exception as e:
                max_tries_exceeded = (tries == max_tries_)
                max_time_exceeded = (max_time_ is not None and
                                     elapsed >= max_time_)

                if giveup(e) or max_tries_exceeded or max_time_exceeded:
                    _call_handlers(on_giveup, *details)
                    raise

                try:
                    seconds = _next_wait(wait, jitter, elapsed, max_time_)
                except StopIteration:
                    _call_handlers(on_giveup, *details)
                    raise e

                _call_handlers(on_backoff, *details, wait=seconds)

                time.sleep(seconds)
            else:
                _call_handlers(on_success, *details)

                return ret
    return retry 
Example #18
Source File: bar.py    From TriFusion with GNU General Public License v3.0 4 votes vote down vote up
def data(self):
        '''
        Variables available:
        - max_value: The maximum value (can be None with iterators)
        - value: The current value
        - total_seconds_elapsed: The seconds since the bar started
        - seconds_elapsed: The seconds since the bar started modulo 60
        - minutes_elapsed: The minutes since the bar started modulo 60
        - hours_elapsed: The hours since the bar started modulo 24
        - days_elapsed: The hours since the bar started
        - time_elapsed: Shortcut for HH:MM:SS time since the bar started
        including days
        - percentage: Percentage as a float
        - dynamic_messages: A dictionary of user-defined DynamicMessage's
        '''
        self._last_update_time = time.time()
        elapsed = self.last_update_time - self.start_time
        # For Python 2.7 and higher we have _`timedelta.total_seconds`, but we
        # want to support older versions as well
        total_seconds_elapsed = utils.timedelta_to_seconds(elapsed)
        return dict(
            # The maximum value (can be None with iterators)
            max_value=self.max_value,
            # Start time of the widget
            start_time=self.start_time,
            # Last update time of the widget
            last_update_time=self.last_update_time,
            # End time of the widget
            end_time=self.end_time,
            # The current value
            value=self.value,
            # The previous value
            previous_value=self.previous_value,
            # The total update count
            updates=self.updates,
            # The seconds since the bar started
            total_seconds_elapsed=total_seconds_elapsed,
            # The seconds since the bar started modulo 60
            seconds_elapsed=(elapsed.seconds % 60) +
            (elapsed.microseconds / 1000000.),
            # The minutes since the bar started modulo 60
            minutes_elapsed=(elapsed.seconds / 60) % 60,
            # The hours since the bar started modulo 24
            hours_elapsed=(elapsed.seconds / (60 * 60)) % 24,
            # The hours since the bar started
            days_elapsed=(elapsed.seconds / (60 * 60 * 24)),
            # The raw elapsed `datetime.timedelta` object
            time_elapsed=elapsed,
            # Percentage as a float or `None` if no max_value is available
            percentage=self.percentage,
            # Dictionary of DynamicMessage's
            dynamic_messages=self.dynamic_messages
        )