本文整理汇总了Python中datetime.timedelta.total_seconds方法的典型用法代码示例。如果您正苦于以下问题:Python timedelta.total_seconds方法的具体用法?Python timedelta.total_seconds怎么用?Python timedelta.total_seconds使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类datetime.timedelta
的用法示例。
在下文中一共展示了timedelta.total_seconds方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_patch_timeout_bigger_than_0
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
def test_patch_timeout_bigger_than_0(
self, service: Service, timeout: timedelta
) -> None:
body = {'timeout': timeout.total_seconds()}
self._send_patch_request(service, body)
self.assertEqual(
floor(timeout.total_seconds()), service.timeout.total_seconds()
)
示例2: fetch_rows
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
def fetch_rows(self, column_names: Tuple, interval: timedelta) -> List[Tuple]:
str_columns: str = ''
column_names = ("Timestamp",) + column_names
for str_column in column_names:
if not str_column:
continue
if str_columns:
str_columns += ', '
str_columns += str_column
str_query: str = 'SELECT {} ' \
'FROM `{}.{}` ' \
'WHERE Timestamp > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL {} SECOND)'. \
format(str_columns, self.bot.bq.dataset_id, self.telemetry_table_id, int(interval.total_seconds()))
print('MonitoringTelegramBot: About to execute query: "{}"'.format(str_query))
job: bigquery.job.QueryJob = self.bot.bq.client.query(str_query, location=self.bot.bq.location)
result: List[Tuple] = []
for row in job.result():
columns: Tuple = ()
for str_column in column_names:
if not str_column:
columns += (None,)
else:
columns += (row.get(str_column),)
result.append(columns)
result.sort(key=lambda x: x[0])
# for r in result:
# print(r)
return result
示例3: modulo_timedelta
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
def modulo_timedelta(dt: datetime, td: timedelta) -> datetime:
"""
Takes a datetime to perform modulo on and a timedelta.
:returns: dt % td
"""
today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
return timedelta(seconds=((dt - today).total_seconds() % td.total_seconds()))
示例4: get_cool_off_iso8601
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
def get_cool_off_iso8601(delta: timedelta) -> str:
"""
Return datetime.timedelta translated to ISO 8601 formatted duration for use in e.g. cool offs.
"""
seconds = delta.total_seconds()
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
days_str = f'{days:.0f}D' if days else ''
time_str = ''.join(
f'{value:.0f}{designator}'
for value, designator
in [
[hours, 'H'],
[minutes, 'M'],
[seconds, 'S'],
]
if value
)
if time_str:
return f'P{days_str}T{time_str}'
return f'P{days_str}'
示例5: schedule_next
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
def schedule_next(self, delay: datetime.timedelta):
self._next_expected = datetime.datetime.now() + delay
if self.scheduler is None:
delay_secs = delay.total_seconds()
default_run_worker(delay_secs, self)
else:
self.scheduler.add(delay, self)
示例6: test_that_setting_valid_timeout_changes_it
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
def test_that_setting_valid_timeout_changes_it(
self, timeout: timedelta
):
self.service.timeout = timeout
self.assertEqual(
timeout.total_seconds(), self.service.timeout.total_seconds()
)
示例7: validate_timeout
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
def validate_timeout(self, timeout: timedelta):
if timeout.total_seconds() < 0:
raise ValidationError(
'Attempted to set a negative timeout duration'
)
else:
return True
示例8: mark_as_failed
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
def mark_as_failed(self, identifier: str, requeue_delay: timedelta=timedelta(0)):
self._queue.mark_finished(identifier)
self._queue.mark_dirty(identifier, requeue_delay)
logging.debug('%s has been marked as failed', identifier)
# Broadcast the change after the requeue delay
# FIXME? Timer's interval may not be 100% accurate and may also
# not correspond with the database server; this could go out of
# synch... Add a tolerance??
Timer(requeue_delay.total_seconds(), self._broadcast).start()
示例9: __init__
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
def __init__(self, payload_factory:Callable[..., Iterable], latency:timedelta):
super().__init__()
self._discharge_latency = latency.total_seconds()
self._lock = Lock()
self._payload = payload_factory()
# Start the watcher
self._watcher_thread = Thread(target=self._watcher, daemon=True)
self._watching = True
self._watcher_thread.start()
示例10: batch_raw_query
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
def batch_raw_query(prometheus_endpoint: ParseResult,
start_timestamp: int,
end_timestamp: int,
step: datetime.timedelta,
query: str,
maxpts=11000) -> Iterable[bytes]:
"""Retrieve metrics from a Prometheus database"""
sstep = '{}s'.format(int(step.total_seconds()))
url = urljoin(prometheus_endpoint.geturl(), 'api/v1/query_range')
def sub(sub_start, sub_end):
"""sub"""
payload = [('start', sub_start),
('end', sub_end),
('step', sstep),
('query', query)]
req = requests.get(url, params=payload)
return req.content
delta = end_timestamp - start_timestamp
batch_size = min(delta // int(step.total_seconds()), maxpts) # type: int
for limits in _create_batches(start_timestamp, end_timestamp, batch_size):
sub_start, sub_end = limits
yield sub(sub_start, sub_end)
示例11: mark_as_failed
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
def mark_as_failed(self, identifier: str, requeue_delay: timedelta=timedelta(0)):
if identifier not in self._known_data:
raise ValueError("Not known: %s" % identifier)
with self._lists_lock:
self._assert_is_being_processed(identifier)
self._processing.remove(identifier)
self._failed.append(identifier)
if requeue_delay is not None:
if requeue_delay.total_seconds() == 0:
self._reprocess(identifier)
else:
end_time = self._get_time() + requeue_delay.total_seconds()
def on_delay_end():
if timer in self._timers[end_time]:
self._timers[end_time].remove(timer)
self._reprocess(identifier)
timer = Timer(requeue_delay.total_seconds(), on_delay_end)
self._timers[end_time].append(timer)
timer.start()
else:
self._on_complete(identifier)
示例12: time_ago
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
def time_ago(interval: timedelta) -> str:
ago_string = ''
s = interval.total_seconds()
if (s >= 31536000):
return "{0:-4.1f} years".format(s/31536000)
elif (s >= 2628000):
return "{0:-4.1f} months".format(s/2628000)
elif (s >= 604800):
return "{0:-4.1f} weeks".format(s/604800)
elif (s >= 86400):
return "{0:-4.1f} days".format(s/86400)
elif (s >= 3600):
return "{0:-4.1f} hours".format(s/3600)
elif (s >= 60):
return "{0:-4.1f} minutes".format(s/60)
else:
return "{0:-4.1f} seconds".format(s)
示例13: format_timestamp
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
def format_timestamp(time: datetime.timedelta) -> str:
"""
Convert timedelta to hh:mm:ss.mmm
https://matroska.org/technical/specs/subtitles/srt.html
:param time: Timedelta
:return: Formatted time string
"""
days, seconds = divmod(time.total_seconds(), 24 * 60 * 60)
hours, seconds = divmod(seconds, 60 * 60)
minutes, seconds = divmod(seconds, 60)
milliseconds = int((seconds - int(seconds)) * 1000)
# Floor seconds and merge days to hours
seconds = int(seconds)
hours += days * 24
return f'{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d},{milliseconds:03d}'
示例14: td_format
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
def td_format(td_object: timedelta):
seconds = int(td_object.total_seconds())
periods = [
("year", 60 * 60 * 24 * 365),
("month", 60 * 60 * 24 * 30),
("day", 60 * 60 * 24),
("hour", 60 * 60),
("minute", 60),
("second", 1),
]
strings = []
for period_name, period_seconds in periods:
if seconds > period_seconds:
period_value, seconds = divmod(seconds, period_seconds)
has_s = "s" if period_value > 1 else ""
strings.append("%s %s%s" % (period_value, period_name, has_s))
return ", ".join(strings)
示例15: duration_display
# 需要导入模块: from datetime import timedelta [as 别名]
# 或者: from datetime.timedelta import total_seconds [as 别名]
def duration_display(duration: datetime.timedelta) -> str:
secs = duration.total_seconds()
if secs == 0:
return "no time at all"
hours, secs = divmod(secs, 3600)
minutes, secs = divmod(secs, 60)
result = []
if hours == 1:
result.append("1 hour")
elif hours > 1:
result.append("%d hours" % hours)
if minutes == 1:
result.append("1 minute")
elif minutes > 1:
result.append("%d minutes" % minutes)
if secs == 1:
result.append("1 second")
elif secs > 1:
result.append("%d seconds" % secs)
return lang.join(result)