Checking if a user is less than 18 years old

67 Views Asked by At

Hi im new in programming in python with datetime (and in general to be honest). So im doing a project where I need to check if the user is more than 18 years old. I used timedelta to get the difference between today and the birthday and I want to check about month and days as well

I have this code:

...
import datetime

today = datetime.date.today()

...

birthday= request.form.get('birthday')
birth= datetime.datetime.strptime(birthday,'%Y-%m-%d').date()

year= datetime.timedelta(today.year - birth.year)
month= datetime.timedelta(today.month- birth.month)
day= datetime.timedelta(today.day- birth.day)
...

For checking the date:

...

if year <= datetime.timedelta(18) and month <= datetime.timedelta(0) and day < datetime.timedelta(0):
     flash('must have 18 years old to sign-up', category='error')

...

Is this correct? Is there any clearer way to get everything with less code? Thanks in advance ;)

1

There are 1 best solutions below

4
Tim Roberts On BEST ANSWER

It depends on how accurate you must be. The datetime module is perfectly capable of date arithmetic.

import datetime

today = datetime.date.today()

birthday = request.form.get('birthday')
birth= datetime.datetime.strptime(birthday,'%Y-%m-%d')
age = (today-birth).days / 365.25
print(age)

Depending on the position of the leap years, this might be a day off.

Alternatively:

import datetime

today = datetime.date.today()
ago = datetime.date(today.year-18, today.month, today.day)
print(ago)

birthday = request.form.get('birthday')
birth = datetime.datetime.strptime(birthday,'%Y-%m-%d')
if birth > ago:
    print("Not yet 18...")