本文整理汇总了Python中datetime.timedelta类的典型用法代码示例。如果您正苦于以下问题:Python timedelta类的具体用法?Python timedelta怎么用?Python timedelta使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了timedelta类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_patch_timeout_bigger_than_0
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: validate_timeout
def validate_timeout(self, timeout: timedelta):
if timeout.total_seconds() < 0:
raise ValidationError(
'Attempted to set a negative timeout duration'
)
else:
return True
示例3: timedelta_repr
def timedelta_repr(td: datetime.timedelta) -> str:
"""
:returns: a human readable representation of the provided timedelta object
"""
assert isinstance(td, datetime.timedelta), type(td)
ZERO = {'00', '0'}
td = td.__str__().split(':')
end = []
if td[0] not in ZERO:
end.append('{} hours'.format(td[0]))
if td[1] not in ZERO:
end.append('{} minutes'.format(td[1]))
if td[2] not in ZERO:
end.append('{} seconds'.format(td[2]))
if len(end) > 1:
end.append('and ' + end.pop(-1))
return ', '.join(
val.lstrip('0')
for val in end
)
示例4: get_cool_off_iso8601
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: fetch_rows
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
示例6: schedule_next
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)
示例7: modulo_timedelta
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()))
示例8: test_that_setting_valid_timeout_changes_it
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()
)
示例9: mark_as_failed
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()
示例10: __init__
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()
示例11: batch_raw_query
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)
示例12: mark_as_failed
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)
示例13: time_ago
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)
示例14: format_timestamp
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}'
示例15: td_format
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)