Luke
Luke

Reputation: 31

Python: How do I find age from an inputted date of birth and current date?

I have made a programme where the user it asked to input their date of birth as integers and then I've tried to convert the date of birth to a format to then compare to the current date which is imported. However I'm struggling to identify the different formats of date that can be used in python.

Here is my code:

from datetime import datetime
print("This programme calculates your age from your date of birth")
dd=int(input("What day were you born? "))
mm=int(input("What month were you born, enter the month number:" ))
yyyy=int(input("What year were you born? Enter the full year: "))

today = datetime.today()
b1 = dd,mm,yyyy
newdate1 = datetime.strptime(b1, "%d/%m/%Y")

age = today.year - b1.year - ((today.month, today.day) < (b1.month, b1.day))
print(age)

Upvotes: 0

Views: 421

Answers (1)

Gajanan
Gajanan

Reputation: 464

import datetime

#asking the user to input their birthdate
birthDate = input("Enter your birth date (dd/mm/yyyy)\n>>> ")
birthDate = datetime.datetime.strptime(birthDate, "%d/%m/%Y").date()
print("Your birthday is on "+ birthDate.strftime("%d") + " of " + 
birthDate.strftime("%B, %Y"))

currentDate = datetime.datetime.today().date()

#some calculations here 
age = currentDate.year - birthDate.year
monthVeri = currentDate.month - birthDate.month
dateVeri = currentDate.day - birthDate.day

#Type conversion here
age = int(age)
monthVeri = int(monthVeri)
dateVeri = int(dateVeri)

# some decisions
if monthVeri < 0 :
 age = age-1
elif dateVeri < 0 and monthVeri == 0:
 age = age-1


#lets print the age now
print("Your age is {0:d}".format(age))

Upvotes: 1

Related Questions