T: Time

  1. Introduction
  2. time module

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())
(1999, 8, 10, 17, 21, 16, 1, 222, 1)

Those 9 numbers are, in order:

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

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

import time

while 1:
    t = time.localtime(time.time())
    print 'The time is', t[3], ':', t[4], 'and', t[5], 'sec'.
    time.sleep(1)   # I'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).



This document is part of the Gasp Python Course. You may modify and/or distribute this document as long as you comply with the LiveWires Documentation Licence: a copy of the licence is included as a comment within this document.

For the lore source of these sheets, click here.

Index