Time

Introduction

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.

time module

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).

Telling the time

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:

0
the year
1
the month of the year (January is 1, December is 12)
2
the day of the month
3
the hour of the day (in the 24-hour clock: so 17 means 5pm
4
the minute of the hour
5
the number of seconds past the minute
6
the day of the week (Monday is 0, Sunday is 6)
7
the day number within the year (1 January is 1)
8
1 if daylight saving time is in force, 0 otherwise

So, you can use this to make a simple clock.

import time

while True:
    t = time.localtime(time.time())
    print 'The time is', t[3], ':', t[4], 'and', t[5], 'sec'.
    time.sleep(1)   # We'll explain this in a moment.

Describing the time

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'

Waiting

time.sleep(0.1234) does absolutely nothing for 0.1234 seconds (or as close to that as the machine can manage) and then the machine 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.