Skip to content
Advertisement

How to check if a datetime is in %d/%m/%Y AND if its greater than a certain datetime

I’m trying to make it so that it checks if its in the format I want and if its greater than today’s date. I want it to ask for input until it gets a right answer but I can’t find a way to do so.

while True:
    try:
        x=dt.datetime.strptime(input(), '%d/%m/%Y')
        
        break
    except ValueError:
        print(1)

Advertisement

Answer

You can use the today class method to get a datetime object representing today’s date, and use the > or < operator to compare it to the parsed x:

while True:
    try:
        x = dt.datetime.strptime(input(), '%d/%m/%Y')
        if x > dt.datetime.today():
            break
        else:
            print('before today')
    except ValueError:
        print('wrong format')
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement