The time Module

The time module provides a number of functions that deal with dates and the time within a day. It's a thin layer on top of the C runtime library.

A given date and time can either be represented as a floating-point value (the number of seconds since a reference date, usually January 1, 1970), or as a time tuple.

1.15.1 Getting the Current Time

Example 1-79 shows how you can use the time module to get the current time.

Example 1-79. Using the time Module to Get the Current Time

File: time-example-1.py

import time

now = time.time()

print now, "seconds since", time.gmtime(0)[:6]
print
print "or in other words:"
print "- local time:", time.localtime(now)
print "- utc:", time.gmtime(now)

937758359.77 seconds since (1970, 1, 1, 0, 0, 0)

or in other words:
- local time: (1999, 9, 19, 18, 25, 59, 6, 262, 1)
- utc: (1999, 9, 19, 16, 25, 59, 6, 262, 0)

The tuple returned by localtime and gmtime contains the year, month, day, hour, minute, second, day of the week, day of the year, daylight savings flag. The year number is four digits, the day of week begins with 0 for Monday, and January 1 is day number 1.

1.15.2 Converting Time Values to Strings

You can of course use standard string-formatting operators to convert a time tuple to a string, but the time module also provides a number of standard conversion functions, as Example 1-80 illustrates.

Example 1-80. Using the time Module to Format Dates and Times

File: time-example-2.py

import time

now = time.localtime(time.time())

print time.asctime(now)
print time.strftime("%y/%m/%d %H:%M", now)
print time.strftime("%a %b %d", now)
print time.strftime("%c", now)
print time.strftime("%I %p", now)
print time.strftime("%Y-%m-%d %H:%M:%S %Z", now)

# do it by hand...
year, month, day, hour, minute, second, weekday, yearday, daylight = now
print "%04d-%02d-%02d" % (year, month, day)
print "%02d:%02d:%02d" % (hour, minute, second)
print ("MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN")[weekday], yearday

Sun Oct 10 21:39:24 1999
99/10/10 21:39
Sun Oct 10
Sun Oct 10 21:39:24 1999
09 PM
1999-10-10 21:39:24 CEST
1999-10-10
21:39:24
SUN 283

1.15.3 Converting Strings to Time Values

On some platforms, the time module contains a strptime function, which is pretty much the opposite of strftime. Given a string and a pattern, it returns the corresponding time tuple, as shown in Example 1-81.

Example 1-81. Using the time.strptime Function to Parse Dates and Times

File: time-example-6.py

import time

# make sure we have a strptime function!
try:
 strptime = time.strptime
except AttributeError:
 from strptime import strptime

print strptime("31 Nov 00", "%d %b %y")
print strptime("1 Jan 70 1:30pm", "%d %b %y %I:%M%p")

The time.strptime function is currently only made available by Python if it's provided by the platform's C libraries. For platforms that don't have a standard implementation (this includes Windows), Example 1-82 offers a partial replacement.

Example 1-82. A strptime Implementation

File: strptime.py

import re
import string

MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
 "Sep", "Oct", "Nov", "Dec"]

SPEC = {
 # map formatting code to a regular expression fragment
 "%a": "(?P[a-z]+)",
 "%A": "(?P[a-z]+)",
 "%b": "(?P[a-z]+)",
 "%B": "(?P[a-z]+)",
 "%C": "(?Pdd?)",
 "%d": "(?Pdd?)",
 "%D": "(?Pdd?)/(?Pdd?)/(?Pdd)",
 "%e": "(?Pdd?)",
 "%h": "(?P[a-z]+)",
 "%H": "(?Pdd?)",
 "%I": "(?Pdd?)",
 "%j": "(?Pdd?d?)",
 "%m": "(?Pdd?)",
 "%M": "(?Pdd?)",
 "%p": "(?Pam|pm)",
 "%R": "(?Pdd?):(?Pdd?)",
 "%S": "(?Pdd?)",
 "%T": "(?Pdd?):(?Pdd?):(?Pdd?)",
 "%U": "(?Pdd)",
 "%w": "(?Pd)",
 "%W": "(?Pdd)",
 "%y": "(?Pdd)",
 "%Y": "(?Pdddd)",
 "%%": "%"
}

class TimeParser:
 def _ _init_ _(self, format):
 # convert strptime format string to regular expression
 format = string.join(re.split("(?:s|%t|%n)+", format))
 pattern = []
 try:
 for spec in re.findall("%w|%%|.", format):
 if spec[0] == "%":
 spec = SPEC[spec]
 pattern.append(spec)
 except KeyError:
 raise ValueError, "unknown specificer: %s" % spec
 self.pattern = re.compile("(?i)" + string.join(pattern, ""))
 def match(self, daytime):
 # match time string
 match = self.pattern.match(daytime)
 if not match:
 raise ValueError, "format mismatch"
 get = match.groupdict().get
 tm = [0] * 9
 # extract date elements
 y = get("year")
 if y:
 y = int(y)
 if y < 68:
 y = 2000 + y
 elif y < 100:
 y = 1900 + y
 tm[0] = y
 m = get("month")
 if m:
 if m in MONTHS:
 m = MONTHS.index(m) + 1
 tm[1] = int(m)
 d = get("day")
 if d: tm[2] = int(d)
 # extract time elements
 h = get("hour")
 if h:
 tm[3] = int(h)
 else:
 h = get("hour12")
 if h:
 h = int(h)
 if string.lower(get("ampm12", "")) == "pm":
 h = h + 12
 tm[3] = h
 m = get("minute")
 if m: tm[4] = int(m)
 s = get("second")
 if s: tm[5] = int(s)
 # ignore weekday/yearday for now
 return tuple(tm)

def strptime(string, format="%a %b %d %H:%M:%S %Y"):
 return TimeParser(format).match(string)

if _ _name_ _ == "_ _main_ _":
 # try it out
 import time
 print strptime("2000-12-20 01:02:03", "%Y-%m-%d %H:%M:%S")
 print strptime(time.ctime(time.time()))

(2000, 12, 20, 1, 2, 3, 0, 0, 0)
(2000, 11, 15, 12, 30, 45, 0, 0, 0)

1.15.4 Converting Time Values

Converting a time tuple back to a time value is pretty easy, at least as long as we're talking about local time. Just pass the time tuple to the mktime function, as shown in Example 1-83.

Example 1-83. Using the time Module to Convert a Local Time Tuple to a Time Integer

File: time-example-3.py

import time

t0 = time.time()
tm = time.localtime(t0)

print tm

print t0
print time.mktime(tm)

(1999, 9, 9, 0, 11, 8, 3, 252, 1)
936828668.16
936828668.0

Unfortunately, there's no function in the 1.5.2 standard library that converts UTC time tuples back to time values (neither in Python nor in the underlying C libraries). Example 1-84 provides a Python implementation of such a function, called timegm.

Example 1-84. Converting a UTC Time Tuple to a Time Integer

File: time-example-4.py

import time

def _d(y, m, d, days=(0,31,59,90,120,151,181,212,243,273,304,334,365)):
 # map a date to the number of days from a reference point
 return (((y - 1901)*1461)/4 + days[m-1] + d +
 ((m > 2 and not y % 4 and (y % 100 or not y % 400)) and 1))

def timegm(tm, epoch=_d(1970,1,1)):
 year, month, day, h, m, s = tm[:6]
 assert year >= 1970
 assert 1 <= month <= 12
 return (_d(year, month, day) - epoch)*86400 + h*3600 + m*60 + s

t0 = time.time()
tm = time.gmtime(t0)

print tm

print t0
print timegm(tm)

(1999, 9, 8, 22, 12, 12, 2, 251, 0)
936828732.48
936828732

In 1.6 and later, a similar function is available in the calendar module, as calendar.timegm.

1.15.5 Timing Things

The time module can be used to time the execution of a Python program, as Example 1-85 demonstrates. You can measure either "wall time" (real world time), or "process time" (amount of CPU time the process has consumed, thus far).

Example 1-85. Using the time Module to Benchmark an Algorithm

File: time-example-5.py

import time

def procedure():
 time.sleep(2.5)

# measure process time
t0 = time.clock()
procedure()
print time.clock() - t0, "seconds process time"

# measure wall time
t0 = time.time()
procedure()
print time.time() - t0, "seconds wall time"

0.0 seconds process time
2.50903499126 seconds wall time

Not all systems can measure the true process time. On such systems (including Windows), clock usually measures the wall time since the program was started.

The process time has limited precision. On many systems, it wraps around after just over 30 minutes.

Also, see the timing module, which measures the wall time between two events.

Core Modules

More Standard Modules

Threads and Processes

Data Representation

File Formats

Mail and News Message Processing

Network Protocols

Internationalization

Multimedia Modules

Data Storage

Tools and Utilities

Platform-Specific Modules

Implementation Support Modules

Other Modules



Python Standard Library
Python Standard Library (Nutshell Handbooks) with
ISBN: 0596000960
EAN: 2147483647
Year: 2000
Pages: 252
Authors: Fredrik Lundh

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net