用户输入时间,然后进行比较

时间:2019-04-04 19:00:23

标签: python time compare

将当前时间与没有日期的用户输入时间进行比较

因此,我正在进行照明程序,需要做一些时间比较,以查看我是处于周期中间还是周期外。长话短说,我在将用户的时间输入与datetime模块的格式化时间进行比较时遇到问题:

def userInput():
        try:
            a = datetime.datetime.strptime(input('When you would like to routine to start in HH:MM 24 hour format: '), "%H:%M")
            print (a.strftime("%H:%M"))
        except:
            print ("Please enter correct time in HHMM format")
        return a

def timeComparator(a):
    now = datetime.datetime.now().time()
    #this obtains the current time
    today = a
    #if statement compares input from 
    print("the time now is: ", now)
    if (now < today):
        print ("hello human")
    elif (now > today):
        print ("hello plant")


if __name__=="__main__":

    a = userInput()

    timeComparator(a)

我收到错误消息“类型错误:'datetime.time'和'datetime.datetime'的实例之间不支持'<'”,我猜这意味着比较的格式不兼容。

我不需要日期或其他任何东西,只需要当前时间。我只想比较一下用户输入时间是在当前时间之前还是之后。

1 个答案:

答案 0 :(得分:0)

函数today中的timeComparatordatetime对象,而您的nowtime对象。只需确保您的user_input返回一个time对象:

def userInput():
    try:
        a = datetime.datetime.strptime(input('When you would like to routine to start in HH:MM 24 hour format: '), "%H:%M").time() #<----- added .time()
        print (a.strftime("%H:%M"))
    except:
        print ("Please enter correct time in HHMM format")
    return a