I'm trying to create a small python3 script that checks whether the typed unix-time is between current unix-time and two weeks into the future.
#Ask for the UNIX execution time.
execution_time = input("When do you want to execute your command?: ")
if len(execution_time) <=0:
print("Error: You have set a UNIX-time")
if (time.time()) < execution_time < (time.time())+1.2e6:
print("The execution time is valid")
if execution_time < (time.time()):
print("The execution time is in the past")
if execution_time > (time.time())+1.2e6:
print("Error:The execution time is more than 2 weeks into the future")
However the error I get is:
Traceback (most recent call last):
File "flightplanner.py", line 38, in <module>
if (time.time()) < execution_time < (time.time())+1.2e6:
TypeError: '<' not supported between instances of 'float' and 'str'
I'm just starting to learn how to program, so there are many if statements which is probably not a good idea, but it is a very small piece of code.
Thank you for any help you can give me.
Best Hasse
The error code says your trying to use “<“ to compare a string (a piece of text) to a float (a number). To the interpreter it’s like you’re saying is “Hello World” smaller than 7? Of course in your case it’s more likely your saying is “1000000000” smaller than 118483939? So what you have to do is take the input, and tell python it should interpret it as a number. You do this using
float(execution_time)
If you want some advise, I’d recommend also using elif (short for else if) and else. An example:
if(num == 1):
print(“Your number was 1”)
elif(num == 2):
print(“Your number was 2”)
else:
print(“Your number was not 1 or 2”)
This has the advantage of being faster, if the first test is successful it will not check for the second and third and it will make the code more readable. Another advantage of else is it will always run if the other tests weren’t successful, even in cases you hadn’t even thought off, or were too lazy to type out.
Another thing I would change, would be to put the time into a variable once, and then use that for comparisons. This is (I think) very slightly faster, and will make it more readable.
Note: every time I’m talking about “faster” it will not make any noticeable differences in your program. Your program should run near-instantaneous, but you can imagine that in longer programs, where you use this a lot, or programs where every performance gain matters, this can make a difference, so it’s better to learn it from the beginning.