当前位置: 首页>>代码示例>>Python>>正文


Python timedelta.total_seconds方法代码示例

本文整理汇总了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()
     )
开发者ID:whitewhim2718,项目名称:TopChef,代码行数:10,代码来源:test_service_detail.py

示例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
开发者ID:juleek,项目名称:raspberrypi,代码行数:33,代码来源:bots.py

示例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()))
开发者ID:Homebrain,项目名称:Homebrain,代码行数:9,代码来源:utils.py

示例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}'
开发者ID:jazzband,项目名称:django-axes,代码行数:28,代码来源:helpers.py

示例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)
开发者ID:kanosaki,项目名称:PicDump,代码行数:9,代码来源:scheduler.py

示例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()
     )
开发者ID:whitewhim2718,项目名称:TopChef,代码行数:9,代码来源:test_service.py

示例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
开发者ID:whitewhim2718,项目名称:TopChef,代码行数:9,代码来源:service_modifier.py

示例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()
开发者ID:wtsi-hgi,项目名称:cookie-monster,代码行数:12,代码来源:biscuit_tin.py

示例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()
开发者ID:MMesbahU,项目名称:cookie-monster,代码行数:14,代码来源:dream_catcher.py

示例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)
开发者ID:cgeoffroy,项目名称:son-analyze,代码行数:25,代码来源:batch.py

示例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)
开发者ID:wtsi-hgi,项目名称:cookie-monster,代码行数:26,代码来源:in_memory_cookiejar.py

示例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)
开发者ID:festen,项目名称:dotfiles,代码行数:19,代码来源:common.py

示例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}'
开发者ID:PetterKraabol,项目名称:Twitch-Chat-Downloader,代码行数:20,代码来源:srt.py

示例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)
开发者ID:Ameobea,项目名称:misc_scripts,代码行数:21,代码来源:__main__.py

示例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)
开发者ID:irmen,项目名称:Tale,代码行数:22,代码来源:util.py


注:本文中的datetime.timedelta.total_seconds方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。