首页 > 解决方案 > 如何在 Python 3 中计算时间?

问题描述

我想要一个代码来显示某人在语音通道中的完成时间,但我不知道如何启动和停止计数器。

    @bot.event
    async def on_voice_state_update(before, after):

        if after.voice.voice_channel:
            timestrr = time.strftime("%d.%m.%Y-%H:%M:%S")
            voicezeit(after.id, timestrr)
    #here should a timer start
        else:
             #and here should the timer stop

我真的不知道该怎么做,所以我真的很感激每一个帮助。

标签: pythonpython-3.xdiscorddiscord.py

解决方案


如果您只想测量两点之间经过的挂钟时间,可以使用 time.time():

import time

start = time.time()
print("hello")
end = time.time()
print(end - start)

这给出了以秒为单位的执行时间。

自 3.3 以来的另一个选项可能是使用perf_counteror process_time,具体取决于您的要求。在 3.3 之前建议使用 time.clock. 但是,它目前已被弃用:

在 Unix 上,以浮点数形式返回当前处理器时间,以秒为单位。精度,实际上是“处理器时间”含义的定义,取决于同名 C 函数的精度。

在 Windows 上,此函数返回自第一次调用此函数以来经过的挂钟秒数,作为浮点数,基于 Win32 函数QueryPerformanceCounter()。分辨率通常优于一微秒。

3.3 版后已弃用:此函数的行为取决于平台:根据您的要求使用 perf_counter() 或 process_time() 来获得明确定义的行为。


推荐阅读