简体   繁体   English

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

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

I have tried using this procedure:我试过使用这个过程:

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

When I fill the input of the date_string with "2021-3-3" the output is当我用“2021-3-3”填充 date_string 的输入时,output 是

This is the correct date string format.

But when I do a little change to "2021-03-03" the output is但是当我对“2021-03-03”做一点改动时,output 是

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

How I make the second input to be true.我如何使第二个输入为真。 So, when I input "2021-03-03" the output will also be所以,当我输入“2021-03-03”时,output 也将是

This is the correct date string format.

I also wanna know how to prompt the user until he input the right format, so that when he input the wrong format or value, the output is我也想知道如何提示用户,直到他输入正确的格式,这样当他输入错误的格式或值时,output 是

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

And, the program keep prompting user for input并且,程序不断提示用户输入

This code works on my machine, and it prompts the user to input again if it doesn't succeed.此代码适用于我的机器,如果不成功,它会提示用户再次输入。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM