banner

© 2004-20 ict4u.net

Basic Age calculator

This code converts a string supplied by the user containing a date into a date object
Then using the currnt date calculates the number of days elapsed since the date entered.
NoteTwo versions are given: the first without error checking, the second with



from datetime import datetime

strDoB = input("Enter your date of birth:")
strFormat = '%d/%m/%Y' # The date should be numeric in the format dd/mm/yyyy

objDoB = datetime.strptime(strDoB, strFormat)   #get the users date of birth
# Get current date
objDateNow = datetime.now()
#work out the difference in days between the two dates
dayDiff = objDateNow - objDoB
#Calculate days difference - allows for leap years
yrsOld = int(dayDiff.days / 365.25)
print("You are {} years old, ".format(yrsOld)))

    


from datetime import datetime

strDoB = input("Enter your date of birth:")
strFormat = '%d/%m/%Y' # The date should be numeric in the format dd/mm/yyyy
try:
	objDoB = datetime.strptime(strDoB, strFormat)   #get the users date of birth
	objDateNow = datetime.now()
	dayDiff = objDateNow - objDoB
	yrsOld = int(dayDiff.days / 365.25)
	assert yrsOld >= 18
	print("At {} years old, ".format(yrsOld),end="")
	print(" you are {:d} year(s) over 18".format(yrsOld - 18))
	# error handling part
except (ValueError):
	print("Invalid date entered")

except AssertionError:
	print("You will have to wait {:d} years until you are 18!".format(18 - yrsOld))