输入日期时处理错误

Handling errors when inputting dates

我有一个 Python 脚本要求用户输入今天的日期。我正在使用的方法给了我一个错误,我发现这个错误让我很困惑,无法找出错误。我想要做的是要求用户输入今天的日期,然后如果日期不是“mm/dd/yyyy”格式则输出一条消息。关于代码和错误的任何建议都会有所帮助。

from datetime import date
todays_date = input("Enter today's date: ")
try:
    todays_date = date.strftime(todays_date, "%m/%d/%Y")
except ValueError:
    print("Error: must be in mm/dd/yyyy ")
    input = input("press 1 to try again or 0 to exit: ")
    if input == "0":
        sys.exit()
print("Today's date is {todays_date}")

错误

todays_date = date.strftime(todays_date, "%m/%d/%Y")
TypeError: descriptor 'strftime' for 'datetime.date' objects doesn't apply to a 'str' object

这里需要的是strptime而不是strftime。它们的功能相反

from datetime import date
todays_date = input("Enter today's date: ")
try:
    todays_date = date.strptime(todays_date, "%m/%d/%Y")
except ValueError:
    print("Error: must be in mm/dd/yyyy ")
    input = input("press 1 to try again or 0 to exit: ")
    if input == "0":
        sys.exit()
print(f"Today's date is {todays_date}") # added f to correct string formatting

在你的情况下不能使用 strftime,因为你有一个字符串格式。 相反,请尝试使用 strptime:

from datetime import datetime
todays_date = datetime.strptime(todays_date, "%m/%d/%Y")