[Tutor] date formatter
Christopher Spears
cspears2002 at yahoo.com
Thu Aug 7 08:01:02 CEST 2008
Hey,
I'm working on a problem out of Core Python Programming (2nd Edition). Basically, I'm creating a class that formats dates. Here is what I have so far:
#!/usr/bin/python
import time
class date_format(object):
def __init__(self, month, day, year):
month_dict = {("jan","january") : 1,
("feb","february") :2,
("mar", "march") : 3,
("apr", "april") : 4,
("may") : 5,
("jun", "june") : 6,
("jul", "july") : 7,
("aug", "august") : 8,
("sep", "september") : 9,
("oct", "october"): 10,
("nov", "november"): 11,
("dec", "december"): 12
}
try:
month = int(month)
except ValueError:
for eachKey in month_dict.keys():
if month.lower() in eachKey:
month = month_dict[eachKey]
else:
month = ""
if month=="" or day=="" or year=="":
self.date = time.localtime()
else:
self.date = (int(year), month, int(day), 0, 0, 0, 0, 1, -1)
def display(self, format_indicator = None):
if format_indicator == 'MDY':
print time.strftime("%m/%d/%y",self.date)
elif format_indicator == 'MDYY':
print time.strftime("%m/%d/%Y",self.date)
elif format_indicator == 'DMY':
print time.strftime("%d/%m/%y",self.date)
elif format_indicator == 'DMYY':
print time.strftime("%d/%m/%Y",self.date)
elif format_indicator == 'MODYY':
print time.strftime("%b %d, %Y",self.date)
else:
print time.strftime("%a %b %d %Y",self.date)
if __name__ == "__main__":
print "Welcome to the Date Formatter!"
month = raw_input("Please enter a month: ")
day = raw_input("Please enter a day: ")
year = raw_input("Please enter a year: ")
date_obj = date_format(month, day, year)
format_indicator = raw_input("Enter a format indicator: ")
date_obj.display(format_indicator.upper())
I am having trouble dealing with the case where the user actually types in a month's name instead of the number:
io at io-station-1 ./chap13 180> python date_format_v01.py
Welcome to the Date Formatter!
Please enter a month (as a number): Oct
Please enter a day: 31
Please enter a year: 1976
Traceback (most recent call last):
File "date_format_v01.py", line 53, in ?
date_obj = date_format(month, day, year)
File "date_format_v01.py", line 24, in __init__
if month.lower() in eachKey:
AttributeError: 'int' object has no attribute 'lower'
Any suggestions?
-Chris
More information about the Tutor
mailing list