简体   繁体   English

如何为包含两个日期的输入引发可自定义的 ValueError?

[英]How to raise customizable ValueError for input containing two dates?

I am trying to understand raising an exception little better.Below is python code, as you can see I am asking for two date inputs from user.我试图更好地理解引发异常。下面是python代码,如您所见,我要求用户输入两个日期。 If user types "2022" and hit enter it is returning python ValueError with msg "Not enough values to unpack (expected 2, got 1)" .如果用户键入“2022”并按回车键,则返回python ValueError并带有 msg "Not enough values to unpack (expected 2, got 1)" Instead what I would like to do is if user types year,month or date then instead of python default ValueError.相反,我想做的是如果用户输入年、月或日期,而不是 python 默认的 ValueError。 It should raise an Error saying "Incorrect date entered, please enter dates in YYYY-MM-DD format ONLY" and should display the input box again for user to enter correct date.它应该引发一个错误,说“输入的日期不正确,请仅输入 YYYY-MM-DD 格式的日期”,并且应该再次显示输入框以供用户输入正确的日期。 My question is how to raise customizable ValueError and ask the user to renter the dates?我的问题是如何提出可定制的 ValueError 并要求用户租用日期?

Any help will be appreciated!任何帮助将不胜感激!

Code代码

def validate(date_text):
        try:
            for y in date_text:
                if not datetime.datetime.strptime(date_text, '%Y-%m-%d'):
                    raise ValueError
                else:
                    return True
        except ValueError:
            print("Incorrect date format, please enter dates in YYYY-MM-DD format ONLY")
            return False
while True:
    start_date,end_date= input("Enter employee start and termination date separated by (,)  in YYYY-MM-DD format only: ").split(",")
    if validate(start_date) and validate(end_date):
        break

You get ValueError: not enough values to unpack (expected 2, got 1) because your are setting 2 variables to input('...').split(',') .您得到ValueError: not enough values to unpack (expected 2, got 1)因为您将 2 个变量设置为input('...').split(',') They expect a string consisting of 2 parts, divided by a comma.他们期望一个由 2 部分组成的字符串,用逗号分隔。 For example if you input a string with more than one comma, you will get too many values to unpack .例如,如果你输入一个包含多个逗号的字符串,你会得到too many values to unpack

Its got to be like this:它必须是这样的:

Enter two values divided by a comma:1,2

Then, i find that your first raise ValueError statement is not necessary.然后,我发现您的第一个raise ValueError语句是不必要的。 If the argument to datetime.datetime.strptime is incorrect it won't go to that raise anyway.如果datetime.datetime.strptime的参数不正确,它无论如何都不会进行该raise

I would dispose of it, along with the if block:我会把它和if块一起处理掉:

import datetime
def validate(date_text):
        try:
            datetime.datetime.strptime(date_text, '%Y-%m-%d')
            return True
        except ValueError:
            print("Incorrect date format, please enter dates in YYYY-MM-DD format ONLY")
            return False
while True:
    start_date,end_date= input("Enter employee start and termination date separated by (,)  in YYYY-MM-DD format only: ").split(",")
    if validate(start_date) and validate(end_date):
        break

I was able to resolve my issue using below code.我能够使用以下代码解决我的问题。 Basically, I needed another try & except block in while statement.基本上,我需要另一个 try & except 语句块。 Thanks @Иван Балван for feedback!感谢@Иван Балван 的反馈!

def validate(date_text):
        try:
            datetime.datetime.strptime(date_text, '%Y-%m-%d')
            return True
        except ValueError:
            print("Incorrect date format, please enter dates in YYYY-MM-DD format ONLY")
            return False

while True:
    try:
        start_date,end_date= input("Enter employee start and termination date separated by (,)  in YYYY-MM-DD format only: ").split(",")
        if validate(start_date) and validate(end_date):
            break
    except ValueError:
        print("Incorrect date enetered, please enter both dates in YYYY-MM-DD format ONLY")

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

相关问题 如何引发ValueError? - How to raise a ValueError? 如何使用raise ValueError? - How to use raise ValueError? 你如何为 Python 类中有价值的输入引发 ValueError? - How do you raise ValueError for input valuable in Python class? 如何解决 raise ValueError(“bad input shape {0}”.format(shape)); ValueError: 错误的输入形状 (977, 57) - How to resolve raise ValueError(“bad input shape {0}”.format(shape)); ValueError: bad input shape (977, 57) raise ValueError(“无效的 DER 输入:数据不足”) ValueError:无效的 DER 输入:数据不足。 如何解决此错误 - raise ValueError(“Invalid DER input: insufficient data”) ValueError: Invalid DER input: insufficient data. How to solve this Error 如何在特定于 python 的 ValueError 中引发? - How can I raise in python specific ValueError? 如何测试负数并引发 ValueError? - How to test for negative number and raise ValueError? python - 当存在AssertionError时如何引发ValueError? - How to raise ValueError when AssertionError is present python? Scikit-fuzzy 出现错误 raise ValueError("意外输入:" + key) - Scikit-fuzzy getting error raise ValueError("Unexpected input: " + key) 使用 raise ValueError python 允许两种日期时间格式 - Allow two datetime format using raise ValueError python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM