Issue
I am practicing by creating an age calculator which calculates age in years based on given date of birth.
However it doesn't work the way I intend it to function. I want to show age in year e.g 19 to the user when their age is 19 and month is less than 6 and if the month is more than 6 then I want to add 1 to the age in this case 19+1.
Can anyone create the same program with the same concept in a better way? Please add some explanation so that it is easy for me to understand.
I am python beginner, so please excuse my bad code as well as my bad English. Thanks in advance for the help.
from datetime import date
Doby,Dobm,Dobd =input("enter your DOB : i.e year,month,days 1999,02,08 : ").split(",")
born = date(year = int(Doby) , month= int(Dobm) , day= int(Dobd))
today = date.today()
age = today.year - born.year
condition = today.month - born.month
if condition >= 6 :
age += 1
elif condition <= -6 :
age -= 1
print(age)
Solution
here is your function
def years_of_age():
from datetime import date, datetime
dob = input("Please enter your DOB as mm-dd-yyyy: ")
#time delta in days
val = date.today().toordinal() - datetime.strptime(dob, "%m-%d-%Y").toordinal()
# this is just so you can confirm, comment out the following 4 lines
print("months {}, years {}".format(\
int(datetime.fromordinal(val).strftime("%m")),\
int(datetime.fromordinal(val).strftime("%Y"))\
))
# conditional return based on the months figure
if int(datetime.fromordinal(val).strftime("%m")) >=6:
return int(datetime.fromordinal(val).strftime("%Y")) + 1
else:
return int(datetime.fromordinal(val).strftime("%Y"))
Here are a few examples
years_of_age()
Please enter your DOB as mm-dd-yyyy: 5-16-1976
months 1, years 44
44
years_of_age()
Please enter your DOB as mm-dd-yyyy: 7-16-1976
months 11, years 43
44
years_of_age()
Please enter your DOB as mm-dd-yyyy: 2-16-1977
months 4, years 43
43
- instance method
.toordinal()
converts a datetime object into a number of days since Jan 1 0000. the instance method
.strftime()
converts a string to a datetime object given that there are format directives datetime ("%m-%d-%Y").since you are a beginner I made sure to use python standard library packages, not because numpy is too advanced, because standard library packages are efficient, great and overlooked.
Answered By - hussam
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.