我的第一个Python程序

#我的第一个Python程序
def is_valid_date(strdate):
    #判断是否是一个有效的日期字符串
    try:
        #判断是否是时间格式
        if ":" in strdate and len(strdate)==5:
             #判断小时是否在0与24之间
            if int(strdate[0:2])>= 0 and int(strdate[0:2])<24:
                #判断分钟是否在0与60之间
                if int(strdate[3:5])>=0 and int(strdate[3:5])<60:
                    return True
    except:
        return False
    
from datetime import datetime,timedelta
while True:
    startTime = input('请输入开始时间:')
    if is_valid_date(startTime):
        startTime = datetime.strptime(startTime,'%H:%M')  # 字符串转日期对象
        endTime = input('请输入结束时间:')
        if is_valid_date(endTime):
            endTime = datetime.strptime(endTime,'%H:%M')  # 字符串转日期对象
            if endTime < startTime:
                endTime = endTime + timedelta(days=1)
            Time = endTime-startTime
            print("您的所用时长为:",Time)
        else:
            print("Error1:您输入的时间格式不正确,请重新输入。
时间格式为[小时:分钟]")
    else:
        print("Error2:您输入的时间格式不正确,请重新输入。
时间格式为[小时:分钟]")
        continue


原文地址:https://www.cnblogs.com/yejingping/p/8823587.html