我试过这样做:
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-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
,程序不断提示用户输入。
发布于 2021-04-27 06:18:56
这段代码在我的机器上工作,如果没有成功,它会提示用户再次输入。
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")
https://stackoverflow.com/questions/67284771
复制