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


Python datetime.timedelta类代码示例

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

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

示例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
    )
开发者ID:Mause,项目名称:pytransperth,代码行数:26,代码来源:trips.py

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

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

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

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

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

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

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

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

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

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

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

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


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