In python, how to check if a date is valid?

You could try doing

import datetime
datetime.datetime(year=year,month=month,day=day,hour=hour)

that will eliminate somethings like months >12 , hours > 23, non-existent leapdays (month=2 has max of 28 on non leap years, 29 otherwise, other months have max of 30 or 31 days)(throws ValueError exception on error)

Also you could try to compare it with some sanity upper/lower bounds.
ex.:

datetime.date(year=2000, month=1,day=1) < datetime.datetime(year=year,month=month,day=day,hour=hour) <= datetime.datetime.now()

The relevant upper and lower sanity bounds depend on your needs.

edit: remember that this does not handle certain datetimes things which may not be valid for your application(min birthday, holidays, outside hours of operation, ect.)

Leave a Comment