class Date:
def __init__(self, digits): #digits='10/20/21'
self.month = digits[:2] #'10'
self.day = digits[3:5] #'20'
self.year = digits[6:8] #'21'
def __str__(self):
return f"Dated this {self.day} day of {self.month}, 20{self.year}"
def checkday(date): #add 'st', 'nd', 'rd', or 'th' to day
if int(date.day) == 1 or int(date.day) == 21 or int(date.day) == 31:
date.day += 'st'
elif int(date.day) == 2 or int(date.day) == 22:
date.day += 'nd'
elif int(date.day) == 3 or int(date.day) == 23:
date.day += 'rd'
else:
date.day += 'th'
def checkmonth(date): #get name of month
date.month = monthdic[date.month]
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'Jul', 'Aug', 'Sep', 'Oct','Nov', 'Dec']
monthdic = {str(i): month for i, month in zip(range(1,13), months)}
date = Date(input("Enter date (mm/dd/yy):\t"))
checkday(date)
checkmonth(date)
print(date)
a couple of errors that come down to one problem that i did not think of:
if it is january: 1/12/14
will not work because self.month
is 1/12/14[:2]
.
Enter date (mm/dd/yy): 1/12/14
Traceback (most recent call last):
File "date.py", line 38, in <module>
checkday(date)
File "date.py", line 14, in checkday
if int(date.day) == 1 or int(date.day) == 21 or int(date.day) == 31:
ValueError: invalid literal for int() with base 10: '2/'
if i resort to 01/12/14
, this will also not work because 01
is '01'
and monthdic['01']
does not exist:
Enter date (mm/dd/yy): 01/12/14
Traceback (most recent call last):
File "date.py", line 39, in <module>
checkmonth(date)
File "date.py", line 28, in checkmonth
date.month = monthdic[date.month]
KeyError: '01'
obviously
def __init__(self, digits):
self.month = digits[:2]
self.day = digits[3:5]
self.year = digits[6:8]
is not the best approach, what are some good approaches (other than regex) ?
also one thing: would it be appropriate to call checkdate()
and checkmonth
inside __init__
?