Search code examples
pythonpython-3.xdatepython-datetime

I want to get the user date of birth in python


bdate = input("Type your Date of birth (ie.10/11/2011) : ")
print(bdate)
day, month, year = map(int, bdate.split('/'))
birth_date = datetime.date(day, month, year)
print(birth_date)
today = datetime.datetime.now().strftime("%Y")
print(today)
age = today - birth_date.year ```

Error : day is out of range for month how to solve this error


Solution

  • Like @sushanth says you can use relativedelta.

    But to understand what was wrong about your code I have corrected it:

    import datetime
    
    bdate = input("Type your Date of birth (ie.10/11/2011) : ")
    
    day, month, year = map(int, bdate.split('/'))
    birth_date = datetime.date(year, month, day)
    
    current_year = datetime.datetime.now().year
    
    age = current_year - birth_date.year
    
    print(age)
    

    The first problem is, that datetime.date takes the following attributes: year, month, day not day, month, year.

    The second problem is that you cannot subtract a string from an integer. Instead you can use datetime.datetime.now().year to get the current year (int).