Reputation: 353
I want a code that shows the complete time someone has been in a voice channel, but I don't 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
Upvotes: 22
Views: 112865
Reputation: 649
Why do you need a counter? Just initialise start_time
variable to None
in the beginning, then in your if-block you check whether it is set, if it isn't you set it to time.time()
. In the else-block set end_time
to time.time()
again and calculate the difference.
EDIT
I don't know what the layout of the rest of your application, you have to initialise start_time = None
somewhere outside of this update function. You would need to set it for each user, I will assume it is stored as user.start_time
, but again, this is dependent on the structure of your app. Then your function could become this:
@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
Upvotes: 2
Reputation: 69
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
orprocess_time
, depending on your requirements. Before 3.3 it was recommended to usetime.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.
Upvotes: 55