本文整理汇总了Python中datetime.timedelta.total_seconds方法的典型用法代码示例。如果您正苦于以下问题:Python timedelta.total_seconds方法的具体用法?Python timedelta.total_seconds怎么用?Python timedelta.total_seconds使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类datetime.timedelta
的用法示例。
在下文中一共展示了timedelta.total_seconds方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dump_age
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
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)
示例2: dump_age
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
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)
示例3: _check_timetable
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
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)
示例4: bounce
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
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()
示例5: from_timedelta
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
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)
示例6: test_time_delta
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
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')
示例7: AutoCallib
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
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")
示例8: pings
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
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})
示例9: __post_init__
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
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()
示例10: retry_predicate
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
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
示例11: retry_exception
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
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
示例12: data
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
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
)