當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。