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

mrfwxfqh  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(265)

我试过使用这个程序:

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”填充日期字符串的输入时,输出是

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

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

ybzsozfc

ybzsozfc1#

这段代码在我的机器上运行,如果没有成功,它会提示用户再次输入。

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")

相关问题