比较python中的日期(3.3.3)

Eri*_*vas 0 python time date

我必须要求用户输入开始日期和结束日期.日期必须是YYYY-MM-DD格式.我已经编写了一些if语句来处理用户可能会做出的一些格式错误,例如不在其间输入破折号,以及在彼此的位置输入月份和日期.

我现在需要的是确保结束日期始终晚于开始日期的方法.从逻辑上讲,结束日期不能在开始日期之前发生.

我不知道有办法做到这一点.任何帮助将不胜感激,谢谢.

def get_start_date() -> str:
    START_DATE = input('Enter start date (in YYYY-MM-DD format): ').strip()

    if len(START_DATE) != 10:
        print('Date entry not correct, please try again')
        get_start_date()

    elif eval(START_DATE[5]) > 1:
        print('Date entry not correct, please try again')
        get_start_date()

    elif eval(START_DATE[8]) > 3:
        print('Date entry not correct, please try again')
        get_start_date()

    elif START_DATE[4] and START_DATE[7] != '-':
        print('Date entry not correct, please try again')
        get_start_date()



def get_end_date() -> str:
    END_DATE = input('Enter end date (in YYYY-MM-DD format): ').strip()

    if len(END_DATE) != 10:
        print('Date entry not correct, please try again')
        get_end_date()

    elif END_DATE[4] and END_DATE[7] != '-':
        print('Date entry not correct, please try again')
        get_end_date()

    elif eval(END_DATE[5]) > 1:
        print('Date entry not correct, please try again')
        get_end_date()



get_start_date()
get_end_date()
Run Code Online (Sandbox Code Playgroud)

jon*_*rpe 6

你可以简化这段代码; 获取开始日期与获取结束日期非常相似,datetime模块将为您完成大量工作:

from datetime import datetime

def get_date(prompt, f="%Y-%m-%d"):
    while True:
        try:
            return datetime.strptime(input(prompt), f)
        except ValueError:
            print("Not a valid date.")
Run Code Online (Sandbox Code Playgroud)

现在您将返回一个实际datetime对象,而不仅仅是一个字符串,并且可以轻松地进行比较:

start = get_date("Enter start date (YYYY-MM-DD): ")
while True:
    end = get_date("Enter end date (YYYY-MM-DD): ")
    if end > start:
        break
    print("End must be later than start.")
Run Code Online (Sandbox Code Playgroud)