[Tutor] date formatter

bob gailer bgailer at gmail.com
Thu Aug 7 13:19:58 CEST 2008


Christopher Spears wrote:
> 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:
>   

Consider reformatting the month_dict so each name and abbreviation is a 
key. Then you can just look up the potential key rather than looping 
thru all the keys. That is what dictionaries are for!:

	month_dict = {"jan" : 1,
		      "january" : 1,
		      "feb" : 2,
                      "february" :2, etc ...}
        ...
	except ValueError:
		 if month.lower() in month_dict:
                      month = month_dict[month.lower()]
		 else:
		      month = ""

The dict function is also handy here:

	month_dict = dict(
                       jan = 1,
		       january = 1,
		       feb = 2,
                       february = 2, etc ...)


Consider using another dictionary for the formats:

	format_dict = dict(
		 MDY = "%m/%d/%y",
		 MDYY = "%m/%d/%Y",
		 DMY = "%d/%m/%y",
		 DMYY = "%d/%m/%Y",
		 MODYY = "%b %d, %Y",)


> #!/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
>
>
>       
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   



More information about the Tutor mailing list