I\'ve just started learning Python today. I\'ve been reading a Byte of Python. Right now I have a project for Python that involves time. I can\'t find anything relating to t
Try time.time()
, which returns the current time as the number of seconds since a set time called the epoch (midnight on Jan. 1, 1970 for many computers). Here's one way to use it:
import time
max_time = int(raw_input('Enter the amount of seconds you want to run this: '))
start_time = time.time() # remember when we started
while (time.time() - start_time) < max_time:
do_stuff()
So we'll loop as long as the time since we started is less than the user-specified maximum. This isn't perfect: most notably, if do_stuff()
takes a long time, we won't stop until it finishes and we discover that we're past our deadline. If you need to be able to interrupt a task in progress as soon as the time elapses, the problem gets more complicated.