简体   繁体   English

如何在 python 程序中跟踪时间?

[英]How do I keep track of time in a python program?

I am writing a game using Python and Tkinter and I need to display how much time the player has left.我正在使用 Python 和 Tkinter 编写游戏,我需要显示玩家还剩多少时间。
I need a function to run regularly and update my time_left variable.我需要一个 function 来定期运行并更新我的time_left变量。
I can't use a while loop because my program will be stuck in it forever.我不能使用while loop ,因为我的程序将永远卡在其中。
How do I keep track of time here?我如何在这里记录时间?

To create a game i think you will still need a loop (game loop).要创建游戏,我认为您仍然需要一个循环(游戏循环)。 Inside that loop, use datetime and timedelta在该循环中,使用datetimetimedelta

from datetime import datetime and timedelta

In your game loop, set a condition;在你的游戏循环中,设置一个条件;

now = datetime.now()
if datetime.now() <= now + timedelta(minutes=How_many_minutes_you_want_to_run_the_game):
    run_the_game
else:
    stop_the_game

Inside that loop you can simply create a variable to store the current time OR final time( datetime.now() + timedelta(minutes=How_many_minutes_you_want_to_run_the_game) - datetime.now() ) which is time remaining.在该循环中,您可以简单地创建一个变量来存储当前时间或最后时间( datetime.now() + timedelta(minutes=How_many_minutes_you_want_to_run_the_game) - datetime.now() ),这是剩余时间。

EXAMPLE:例子:

from datetime import datetime, timedelta
now = datetime.now()
while datetime.now() < (now + timedelta(seconds=2)):
    print(datetime.now())

This code will print the present time for 2 seconds.此代码将打印当前时间 2 秒。 You can also set some delay(delay of 1 sec) to print time after each second passes.您还可以设置一些延迟(延迟 1 秒)以在每秒钟过去后打印时间。

import time
start = time.time()
end = time.time()
time_consumed=end-start;
time_left=10-time_consumed; 

10 being the time limit. 10是时间限制。 You can you this code to start noting and print the time taken by user您可以使用此代码开始记录并打印用户花费的时间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM