Crack the Code: IT Interview Questions and Answers - Programming Language Institute

Python String Practices Questions

 
1

Question- How to calculate the age of the person in Python trough class and method?



Answer-


from datetime import datetime
from dateutil.relativedelta import relativedelta

class Person:
    name=""
    country=""
    dob=""

    def getDetails(self):
         self.name=input("Enter Name")
         self.country=input("Enter Country")
         # Input birth date
         dob_str = input("Enter your birth date (YYYY-MM-DD): ")
         #datetime.strptime(): To convert the input string to a datetime object.
         self.dob = datetime.strptime(dob_str, "%Y-%m-%d")
         
        
    def AgeCalculate(self):
        print()
        print("Person Details::::")
        print("Name : ",self.name)
        print("Country name :",self.country)
        # Get the current date
        current_today = datetime.today()
    
        # Calculate the difference in years, months, and days
        #relativedelta from dateutil: To calculate the difference in years, months, and days easily.
        age = relativedelta(current_today, self.dob)
    
        print("Person Age is: {0} years, {1} months, and {2} days".format(age.years, age.months, age.days))
        
        
    
p1=Person()
p1.getDetails()
p1.AgeCalculate()