📘 How to Calculate Age in Python Using Pandas & relativedelta | Datawiz Vamshi

One of the most common Python beginner projects is building an Age Calculator.


But instead of calculating just the number of years, we can use Pandas + relativedelta to calculate a person’s exact age in:

✔ Years
✔ Months
✔ Days

This makes your output more accurate and professional.


🔍 Step 1: Import Required Libraries

We need three main modules:

import pandas as pd from datetime import datetime from dateutil.relativedelta import relativedelta
  • pandas – helps convert string input into date format

  • datetime – fetches today’s date

  • relativedelta – calculates difference in Y/M/D format


🧠 Step 2: Take User Input (DD-MM-YYYY Format)

We accept DOB from the user:

dob_user = pd.to_datetime( input('Enter your Date of Birth (DD-MM-YYYY): '), format='%d-%m-%Y' ).date()

📅 Step 3: Get Today's Date

today = datetime.today().date()

🧮 Step 4: Calculate Exact Age

dob = relativedelta(today, dob_user)

🖨 Step 5: Print the Final Age

print(f'Your Date of Birth: {dob_user}\nYour Age is {dob.years} Years, {dob.months} Months, {dob.days} Days..!')

🏁 Output Example

Your Date of Birth: 1997-03-15 Your Age is 27 Years, 8 Months, 9 Days..!

💡 Why Use relativedelta?

relativedelta automatically adjusts:
✔ Leap years
✔ Month lengths
✔ Day rollovers

This makes it more accurate than subtracting raw dates.


🚀 Final Thoughts

This is a perfect project for beginners to understand:

  • User input handling

  • Python date operations

  • Real-world age calculation

  • Working with Pandas and relativedelta

Post a Comment

0 Comments