如何在Python 3中计算时间?

23

我想要一个代码,可以显示某人在语音频道中的完整时间,但我不知道如何开始和停止计时器。

@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

我希望计时器从A开始,到B停止,然后记录时间。 - Deniz Ascherl
你想一直显示一个计时器,以显示自某人进入频道以来的时间吗?https://dev59.com/6GYr5IYBdhLWcg3wLXSh 这个链接有帮助吗? - Aurgho Bhattacharjee
为什么不直接使用 time.time() 记录 A 点和 B 点的时间? - tonypdmtr
准确地说,将B-A作为秒数,并相应地除以60和60*60,即可得到分钟和小时。 - Aurgho Bhattacharjee
你需要将结束时间[B]减去开始时间[A]。 - tonypdmtr
2个回答

52

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

import time

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

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

自3.3版本以来,另一个选择是使用perf_counterprocess_time,具体取决于您的要求。在3.3之前,建议使用time.clock。但是,它目前已弃用:

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

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

自3.3版本以来已弃用:此函数的行为取决于平台:根据您的要求使用perf_counter()process_time()以获得良好的定义行为。


2
为什么需要计数器?只需在开头将start_time变量初始化为None,然后在if块中检查它是否已设置,如果没有,则将其设置为time.time()。在else块中再次将end_time设置为time.time()并计算差异即可。
编辑:我不知道您的应用程序的其余布局,您需要在此更新函数之外的某个地方初始化start_time = None。您需要为每个用户设置它,我将假设它存储为user.start_time,但这取决于您的应用程序结构。然后您的函数可以变成这样:
    @bot.event
    async def on_voice_state_update(before, after):

        if after.voice.voice_channel:
            if not user.start_time:  # this was set to None somewhere else
                user.start_time = time.time()
            # import datetime from datetime at the top of your file
            timestrr = datetime.from_timestamp(user.start_time).strftime("%d.%m.%Y-%H:%M:%S")
            voicezeit(after.id, timestrr)
        else:
             end_time = time.time()
             voice_chat_time = end_time - after.user.start_time

在使用time.time()函数时,我遇到的一个问题是必须从time中导入time模块,而当我这样做时,timestrr函数就无法工作了。 - Deniz Ascherl
这是因为strftime是一个日期时间函数。如果您需要使用它,可以导入datetime并将变量设置为datetime.datetime.now() - iuvbio
抱歉,time 模块确实有 strftime,但它只能用于当前时间。您也可以同时使用 time.time()datetime.datetime.from_timestamp(start_time).strftime("%d.%m.%Y-%H:%M:%S") 来获取字符串。 - iuvbio
它给我抛出了这个错误:“UnboundLocalError:在赋值之前引用本地变量'start_time'”。 - Deniz Ascherl
是的,你需要先赋值 start_time。我会更新我的答案以使其更清晰。 - iuvbio
如果您编辑问题以提供更多上下文,我很乐意再次更新我的答案。从我所了解的比特中,您可能希望在设置voice_state.voice.voice_channel=True时设置start_time - iuvbio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接