2

Comparing the current time with a user input time WITHOUT the date

So I'm making a lighting routine and I need to do some time comparisons to see if I'm in the middle of a cycle or out of a cycle. Long story short, I'm having issues comparing a user input of time with the formatted time of the datetime module:

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)

I'm getting the error "TypeError: '<' not supported between instances of 'datetime.time' and 'datetime.datetime'" which I guess means the formatting for comparing isn't compatible.

I DON'T need the date or anything else, just the current time. I'd like to just be able to compare if a user input time is before or after the current time.

igomez
  • 39
  • 5

1 Answers1

0

Your today in the function timeComparator is a datetime object while your now is a time object. Just make sure your user_input returns a time object:

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
MooingRawr
  • 4,901
  • 3
  • 24
  • 31
  • That was it thank you!!! I'm not sure I fully understand however. So what kind of object was datetime.datetime before .time() was added? Don't they have the same kind information? – igomez Apr 04 '19 at 19:16
  • `datetime` contains the date with it. `time` is only the time. The module doesn't know how to compare the two. That's the issue. – MooingRawr Apr 04 '19 at 19:26
  • I've been reading about it more and the datetime module and now it makes more sense now that you're explaining it. Thanks again – igomez Apr 04 '19 at 20:14