简体   繁体   中英

how to convert time values (in string) to datetime in python?

so I've been trying to work on a statement where i am supposed to take in time value from the user and if it is between certain time values, I am supposed to greet the user with good morning,, good after noon. good evening and good night: The user will input time in the format HH:MM.SS: my code for the function looks something like this:

r = datetime.time(12, 00, 00)
t = datetime.time(18, 00, 00)
u = datetime.time(6, 00, 00)
p = datetime.time(23, 59, 00)
def my_function:
time=input('what is the time?')
    if datetime.datetime.strptime(time, '%H:%M:%S')>=u and datetime.datetime.strptime(time, '%H:%M:%S')<r:
        print('Morning')
    elif datetime.datetime.strptime(time, '%H:%M:%S')>=r and datetime.datetime.strptime(time, '%H:%M:%S')<t:
        print('Afternoon')
    elif datetime.datetime.strptime(time, '%H:%M:%S')>=t and datetime.datetime.strptime(time, '%H:%M:%S')<p:
        print('Evening')
    elif datetime.datetime.strptime(time, '%H:%M:%S')>=p and datetime.datetime.strptime(time, '%H:%M:%S')<u:
        print('Night')
    else:
        return 'invalid'

i am returned with the error time data 'what is the time?' does not match format '%H:%M:%S' when i try to call the function. Can anyone give any suggestion on how to modify my code or what i am doing wrong? thanks in advance

edit: It gives the error '>=' not supported between instances of 'datetime.datetime' and 'datetime.time'

def my_function():

    r = datetime.time(12, 00, 00)
    t = datetime.time(18, 00, 00)
    u = datetime.time(6, 00, 00)
    p = datetime.time(23, 59, 00)

    time = input('what is the time?')
    time = datetime.datetime.strptime(time, '%H:%M:%S').time()

    if u <= time < r:
        return('Morning')
    elif r <= time < t:
        return('Afternoon')
    elif t <= time < p:
        return('Evening')
    elif p <= time or time < u:
        return('Night')
    else:
        return 'invalid'

 print(my_function())

I think you are missing input('what is the time') so your variable is the string question instead of whatever you're typing into the terminal/calling your function. In addition, the code above needs an indentation after the function definition.

time = input('What is the time?"

right now, you're setting time equal to a python tuple with one string inside of it... "Where is the time?". A tuple is kind of like a list, but with () instead of [].

When you pass the variable 'time' to datetime, what you're literally passing is this: ("What is the time?")

It shouldn't return an error on passing anything to datetime unless it's already asked the user for input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM