如何在 Python 中设置最小和最大日期以验证输入?

How do you set a minimum and maximum date in Python to validate against input?

标题中的问题。我正在编写一个程序,要求用户以 mm/dd/yy 格式输入日期,验证该日期是否仅在 2013 年,然后以这种格式打印日期:2013 年 7 月 1 日。我我只是遇到一个逻辑错误,即使年份不是 2013 年,程序仍会打印日期。这是我的代码:

import datetime


def main():
    def date_method(user_date):
        date_list = user_date.split('/')
        month = int(date_list[0])
        day = int(date_list[1])
        year = 2000 + int(date_list[2])
        try:
            datetime.datetime.min = 1/1/2013
            datetime.datetime.max = 12/31/2013
            the_date = datetime.date(month, day, year)
            correct_date = "True"
            return the_date, correct_date
        except ValueError as err:
            print(err)
            the_date = 1/1/1
            correct_date = "False"
            return the_date, correct_date

    correct_date = "False"
    while correct_date == "False":
        user_date = str(input("Please enter a date in the month/day/year format: mm/dd/yy. "))
        the_date, correct_date = date_method(user_date)
        if correct_date == "True":
            print("Date: ", datetime.date.strftime(the_date, "%B %d, %y"))

main()

我认为我不对的地方是我的 datetime.datetime.min 和 datetime.datetime.max 变量。

设置 datetime.datetime.mindatetime.datetime.max 对我来说就像全局变量。更好的解决方案是简单地检查它是否在一个范围内。

import datetime

def date_method(user_date):
    date_list = user_date.split('/')
    month = int(date_list[0])
    day = int(date_list[1])
    year = 2000 + int(date_list[2])
    the_date = datetime.date(year, month, day)
    if datetime.date(2013, 1, 1) <= the_date <= datetime.date(2013, 12, 31):
        return the_date, True
    else:
        print("Date entered is not in the year 2013.")
        return datetime.date(1, 1, 1), False

def main():
    correct_date = False
    while correct_date == False:
        user_date = input("Please enter a date in the month/day/year format: mm/dd/yy. ")
        the_date, correct_date = date_method(user_date)
        if correct_date:
            print("Date: ", datetime.date.strftime(the_date, "%B %d, %y"))

main()

您的代码中还有一些错误:

  • 您使用字符串 "True""False" 而不仅仅是 TrueFalse.
  • datetime.date(year, month, day)而不是datetime.date(month, day, year)
  • 为什么要在 main() 中定义 date_method
  • 运算符 / 不能像您的示例中那样用于日期。您真正要做的只是除以一个数字,然后 Python 将该数字解析为日期。 (这与您所说的日期完全不同)

Python 内置类型不可变的所以你不能设置任何属性,如果你想验证年份只需转换为日期时间对象并检查 .year 属性为 >= 13.

if mn_year <= dt.year <= mx_year

即使你可以 1/1/2013 是方程式而不是日期。

类似于以下内容:

user_date = input("Please enter a date in the month/day/year format: mm/dd/yy. ")

def date_method(user_date):
    try:
        mn, dy, year = user_date.split('/')
        the_date = datetime.datetime.strptime("{} {} {}".format(mn, dy, year), "%d %m %y")
        if the_date.year >= 2013:
            correct_date = "True"
            return the_date.year, correct_date
    except ValueError as err:
        print(err)
        ....

如果您想要最小值和最大值,请使用上面的 mn_year 和 mx_year。您不需要强制转换为整数,您可以像上面那样使用字符串使用 datetime.strptime。您也不需要将输入强制转换为 str,这正是它的本质。拆分和解包 try 中的 user_date 字符串也会在用户输入错误数据时捕获。