[英]How can I count time in 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
如果您只想測量兩點之間經過的掛鍾時間,可以使用 time.time():
import time
start = time.time()
print("hello")
end = time.time()
print(end - start)
這給出了以秒為單位的執行時間。
自 3.3 以來的另一個選項可能是使用
perf_counter
或process_time
,具體取決於您的要求。 在 3.3 之前,建議使用time.clock
。 但是,它目前已被棄用:
在 Unix 上,以浮點數形式返回當前處理器時間,以秒為單位。 精度,實際上是“處理器時間”含義的定義,取決於同名 C 函數的精度。
在 Windows 上,此函數根據 Win32 函數QueryPerformanceCounter()
以浮點數形式返回自第一次調用此函數以來經過的掛鍾秒數。 分辨率通常優於一微秒。
3.3 版后已棄用:此函數的行為取決於平台:根據您的要求使用 perf_counter() 或 process_time() 來獲得明確定義的行為。
為什么需要櫃台? 只需在開始時將start_time
變量初始化為None
,然后在您的 if-block 中檢查它是否已設置,如果不是,則將其設置為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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.