Introduction
Credit: Gustavo Niemeyer, Facundo Batista
Today,
last weekend, next year. These terms sound so common. You have
probably wondered, at least once, about how deeply our lives are
involved in the very idea of time. The concept of time surrounds us,
and, as a consequence, it's also present in the vast
majority of software projects. Even very simple programs may have to
deal with timestamps, delays, timeouts, speed gauges, calendars, and
so on. As befits a general-purpose language that is proud to come
with "batteries included,"
Python's standard library offers solid support for
these application needs, and more support yet comes from third-party
modules and
packages.
Computing tasks involving money are another interesting topic that
catches our attention because it's so closely
related to our daily lives. Python 2.4 introduced support for decimal
numbers (and you can retrofit that support into 2.3, see http://www.taniquetil.com.ar/facundo/bdvfiles/get_decimal.html),
making Python a good option even for computations where you must
avoid using binary floats, as ones involving money so often are.
This chapter covers exactly these two topics, money and time.
According to the old saying, maybe we should claim the chapter is
really about a single topic, since after all, as
everybody knowstime is money!
The time Module
Python Standard
Library's time module lets Python
applications access a good portion of the time-related functionality
offered by the platform Python is running on. Your
platform's documentation for the equivalent
functions in the C library will therefore be useful, and some
peculiarities of different platforms will affect Python as well.
One of the most used functions from module time is
the one that obtains the current
timetime.time. This
function's return value may be a little cryptic for
the uninitiated: it's a floating-point number that
corresponds to the number of seconds passed since a fixed instant
called the epoch, which may change depending
on your platform but is usually midnight of January 1, 1970.
To check which epoch your platform uses, try, at any Python
interactive interpreter prompt:
>>> import time
>>> print time.asctime(time.gmtime(0))
Notice we're passing 0 (meaning 0 seconds after the
epoch) to the time.gmtime function.
time.gmtime converts any timestamp (in seconds
since the epoch) into a tuple that represents that precise instant of
time in human terms, without applying any kind of time zone
conversion (GMT stands for "Greenwich mean
time", an old but colorful way to refer to what is
now known as UTC, for "Coordinated Universal
Time"). You can also pass a timestamp (in seconds
since the epoch) to time.localtime, which applies
the current local notion of time zone.
It's important to understand the difference, since,
if you have a timestamp that is already offset
to represent a local time, passing it to the
time.localtime function will
not yield the expected resultunless
you're so lucky that your local time zone happens to
coincide with the UTC time zone, of course!
Here is a way to unpack a tuple representing the current local time:
year, month, mday, hour, minute, second, wday, yday = time.localtime( )
While valid, this code is not elegant, and it would certainly not be
practical to use it often. This kind of construct may be completely
avoided, since the tuples returned by the time functions let you
access their elements via meaningful attribute names. Obtaining the
current month then becomes a simple and elegant expression:
time.localtime( ).tm_mon
Note that we omitted passing any argument to
localtime. When we call
localtime, gmtime, or
asctime without an argument, each of them
conveniently defaults to using the current time.
Two very
useful functions in module time are
strftime, which lets you build a string from a
time tuple, and strptime, which goes the other
way, parsing a string and producing a time tuple. Each of these two
functions accepts a format string that lets you specify exactly what
you want in the resulting string (or, respectively, what you expect
from the string you're parsing) in excruciating
detail. For all the formatting specifications that you can use in the
format strings you pass to these functions, see http://docs.python.org/lib/module-time.html.
One last important function in module time is the
time.sleep function, which lets you introduce
delays in Python programs. Even though this
function's POSIX counterpart accepts only an integer
parameter, the Python equivalent supports a float and allows
sub-second delays to be achieved. For instance:
for i in range(10):
time.sleep(0.5)
print "Tick!"
This snippet will take about 5 seconds to execute, emitting
Tick! approximately twice per second.
Time and Date Objects
|