04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 10 ■ BATTERIES INCLUDED 227<br />

Table 10-6. Some Important Functions in the time Module<br />

Function<br />

asctime([tuple])<br />

localtime([secs])<br />

mktime(tuple)<br />

sleep(secs)<br />

strptime(string[, format])<br />

time()<br />

Description<br />

Converts time tuple to a string<br />

Converts seconds to a date tuple, local time<br />

Converts time tuple to local time<br />

Sleeps (does nothing) for secs seconds<br />

Parses a string into a time tuple<br />

Current time (seconds since the epoch, UTC)<br />

The function time.asctime formats the current time as a string, such as<br />

>>> time.asctime()<br />

'Fri Dec 21 05:41:27 2001'<br />

You can also supply a date tuple (such as those created by localtime) if you don’t want the<br />

current time. (For more elaborate formatting, see the strftime function, described in the standard<br />

documentation.)<br />

The function time.localtime converts a real number (seconds since epoch) to a date tuple,<br />

local time. If you want universal time, use gmtime instead.<br />

The function time.mktime converts a date tuple to the time since epoch in seconds; it is the<br />

inverse of localtime.<br />

The function time.sleep makes the interpreter wait for a given number of seconds.<br />

The function time.strptime converts a string of the format returned by asctime to a date<br />

tuple. (The optional format argument follows the same rules as those for strftime. See the<br />

standard documentation.)<br />

The function time.time returns the current (universal) time as seconds since the epoch.<br />

Even though the epoch may vary from platform to platform, you can reliably time something<br />

by storing the result of time before and after the event (such as a function call) and then computing<br />

the difference. For an example of these functions, see the next section, which covers the random<br />

module.<br />

OTHER TIME FUNCTIONS<br />

The functions shown in Table 10-6 are just a selection of those available from the time module. Most of the<br />

functions in that module perform tasks similar to or related to those described in this section. If you need<br />

something not covered by the functions described here, you should take a look at the section about the time<br />

module in the standard library reference (http://python.org/doc/lib/module-time.html); chances<br />

are you may find exactly what you are looking for.<br />

There are also some more recent time-related modules available: datetime and timeit. You can find<br />

more information about both in the library reference, and timeit is also discussed briefly in Chapter 16.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!