Download - All IT eBooks

Transcript
CHAPTER 11 ■ REUSING CODE WITH MODULES AND PACKAGES
# Report on the total and the priciest purchase
print("You spent {0}".format(total))
print("Your priciest purchase was: {0[1]} {0[0]}s, at a total cost of
{0[3]}".format(priciest))
Let’s try it out.
% python csv demo.py
You spent 10.92
Your priciest purchase was: 3 Snorklets, at a total cost of 2.97
The csv module can also be used to write CSV files, and you can use either the online
documentation or help(csv) in the interactive prompt to give you more information on how csv can
parse different variations of the CSV format.
datetime
Handling dates and times is always a difficult problem in any language, and it’s tempting for the new
programmer to develop all sorts of string-munging libraries to do quite specific tasks. datetime exists in
Python’s core libraries so that you can resist that temptation, should it ever arise.
The datetime module contains a lot of functionality that we won’t cover explicitly here. However,
Listing 11-8 demonstrates its core features: parsing, creating, and manipulating date and time objects.
Save this code to datetime.py, and run it from the command line.
Listing 11-8. The datetime Module
import datetime
# Date parsing
# Original data in a fairly human-readable format
guess = "19 Feb 2001, 08:23"
# Parsing into a Python object
time obj = datetime.datetime.strptime(guess, "%d %b %Y, %H:%M")
# Printing the object generates a slightly different readable format
print("Python thinks that '{0}' is '{1}'".format(guess,time obj))
# Date manipulation
# Define a time interval of five days
interval = datetime.timedelta(5)
day = datetime.date.today()
for i in range(1,10):
# Count back in intervals of five days
day -= interval
print("{0} days ago was {1}".format(i*5,day))
In Listing 11-8, we have to give strptime() a format mask, which it uses to try to parse the guess
string into the relevant fields for day, month, year, and so on. If strptime() can’t parse the date using the
format specified, it raises a value error exception. Chapter 10 explained how to use exceptions to your
advantage: in this case, you could specify a different date format and try again!
257