0

How can I check with a inputed date if that date of birthday is under 18?

year=int(input("Year born: "))
month = int(input("Month born: "))
day = int(input("Day born: "))
date = date(year,month,day)

What code can I use with date.today() in order to check if user is under 18? Because if I substract 2022- year it could be under 17 because he was born in December

UPDATE:

def is_under_18(birth):
year=int(input("Year born: "))
month = int(input("Month born: "))
day = int(input("Day born: "))
date = date(year,month,day)
now = date.today()
return (
    now.year - birth.year < 18
    or now.year - birth.year == 18 and (
        now.month < birth.month 
        or now.month == birth.month and now.day <= birth.day
    )
)

Should it be like this? I didn't understand. And I would also like to add an if he is older than 18, then print("You are over 18")

  • Convert the input to a `date` using the `date.date()` function. Then subtract that date from `date.today()` to get the difference. Then check if that difference is less than 18 years. – Barmar Nov 22 '22 at 20:51
  • @Barmar And how do you define "18 years" in days as comparison target? It depends on many factors, at least - leap years (and you should add one day, if current year is a leap year and current date is after 28th Dec...). Given that 18 years is an child/adult border in many countries, even 1 day me be a problem and cause penalties by law. – STerliakov Nov 22 '22 at 20:55

1 Answers1

0

You can compare all date parts sequentially:

from datetime import date

def is_under_18(birth):
    now = date.today()
    return (
        now.year - birth.year < 18
        or now.year - birth.year == 18 and (
            now.month < birth.month 
            or now.month == birth.month and now.day <= birth.day
        )
    )

In most countries people are considered to have age of n+1 at the next day after their birthday, so the last comparison uses <=.

You may also consider dateutil library that provides relativedelta class that gives you better difference approach (full years + full months + full days + ...).

The function above accepts one argument (birth), which should be a date inputted by your user.

year = int(input("Year born: "))
month = int(input("Month born: "))
day = int(input("Day born: "))
# Please, STOP using `date` as variable name here!
birth = date(year,month,day)

if is_under_18(birth):
    print('Under 18')
else:
    print('Adult')
STerliakov
  • 4,983
  • 3
  • 15
  • 37