Skip to content
In Python - Taking Date Of Birth as input and finding out the user's age in Years, Months and Days
Profile icon
Archanakumar13

In the Python Programming Language, How can I use the input function to take the user's Date of Birth and use that to find the user's age in Years, Months and Days? I will need to import today's date to do that, right? But, how would the code be written if the date of birth has to be input by the user?

Also, how can I change the format of the Date of Birth that the user will input? Is there a way to change the format of the Date of Birth of the user from the default format to a different format?

You are viewing a single comment. View All
Profile icon
flafflar

@Archanakumar13
Great, now that you are more specfic, I can be more helpful! Python has a lot of date handling utilities, but unfortunately, it doesn't have a convenient way to parse arbitrary dates. There is a great pip module for this though, called python-dateutil. Having installed this, the rest of the program should be very easy. First, import these libraries:

from dateutil.parser import parse from dateutil.relativedelta import relativedelta # Phew, that's a big one from datetime import *

Then, use the parse function to parse the input date:

birth_date = parse(input())

The current date can be obtained with datetime.now:

now = datetime.now()

To calculate the difference between those two dates, use the relativedelta function:

difference = relativedelta(now, birth_date)

Then, you can get the years, months and days of the difference by using the following properties:

difference.years difference.months difference.days

which you should format however you wish.

Hope this helps. And if it did, make sure to mark it as the correct answer!