How can I count time in Python 3?

Deniz Ascherl picture Deniz Ascherl · Jun 22, 2019 · Viewed 31.5k times · Source

I want a code that shows the complet time someone has been in a voicechannel but I dont know how to start and stop a counter.

    @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

I really dont know how to do this so I would really appreciate every help.

Answer

Kais Tounsi picture Kais Tounsi · Jun 22, 2019

If you just want to measure the elapsed wall-clock time between two points, you could use time.time():

import time

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

This gives the execution time in seconds.

Another option since 3.3 might be to use perf_counter or process_time, depending on your requirements. Before 3.3 it was recommended to use time.clock . However, it is currently deprecated:

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.

Deprecated since version 3.3: The behaviour of this function depends on the platform: use perf_counter() or process_time() instead, depending on your requirements, to have a well defined behaviour.