Time is important. So you might want to know how long someone has been using your program, or what time of day it is; you might want to make something happen exactly 10 times per second; in any case, you need to know what Python can do about time. This sheet tells you about that.
If you say import time then after that you can use a number of functions for working with times. If you’re curious about what import means, see Sheet M ( Modules).
time.time() gives the number of seconds since the very beginning of the year 1970. You may think this is a strange way to represent time. You’d be right too, but fortunately Python provides ways of turning this sort of time into something more useful.
time.localtime(t), if t is a time value produced by time.time(), is an object made up of 9 numbers. Here’s what it produced for me using the time right now:
>>> time.localtime(time.time()) (2007, 8, 6, 17, 7, 19, 0, 218, 1)
Those 9 numbers are, in order:
So, you can use this to make a simple clock.
import time while True: t = time.localtime(time.time()) print 'The time is', t, ':', t, 'and', t, 'sec'. time.sleep(1) # We'll explain this in a moment.
There’s a complicated function called time.strftime which lets you print times more neatly. If you want to know the gruesome details, ask your teacher. Here’s a little example.
>>> import time >>> time.strftime('%A, %d %B %Y, at %I:%M%p', time.localtime(time.time())) 'Tuesday, 10 August 1999, at 05:41PM'
time.sleep(0.1234) does absolutely nothing for 0.1234 seconds (or as close to that as the machine can manage) and then the machinen will pick up where it left off. In our earlier example, when we used time.sleep(1), the computer paused for one second, then continued the while loop, printed the new time (one second later), and paused again.