如何使用 datetime 库验证 python 中的字符串输入并不断提示用户输入直到有效输入?

How to validate a string input in python using datetime library and keep prompting user for input until valid input?

我试过使用这个程序:

import datetime
date_string = input()
format = "%Y-%m-%d"

try:
    datetime.datetime.strptime(date_string, format)
    print("This is the correct date string format.")
except ValueError:
    print("This is the incorrect date string format. It should be YYYY-MM-DD")

当我用“2021-3-3”填充 date_string 的输入时,输出是

This is the correct date string format.

但是当我对“2021-03-03”做一点改动时,输出是

This is the incorrect date string format. It should be YYYY-MM-DD

我如何使第二个输入为真。所以,当我输入“2021-03-03”时,输出也将是

This is the correct date string format.

我也想知道如何提示用户直到他输入正确的格式,这样当他输入错误的格式或值时,输出是

This is the incorrect date string format, try again fill the

而且,程序不断提示用户输入

这段代码在我的机器上有效,如果不成功会提示用户重新输入。

import datetime
format = "%Y-%m-%d"

while(True):
    date_string = input("> ").strip()
    try:
        datetime.datetime.strptime(date_string, format)
        print("This is the correct date string format.")
        break
    except ValueError:
        print("This is the incorrect date string format. It should be YYYY-MM-DD")