Would I be able to check if the time is between 12:00 and 13:00 using datetime?

75 views Asked by At

Would I be able to get datetime to tell me if the time is in range of 12:00 to 1300

I have tried variations of things like:

import datetime
current_time = datetime.datetime.now().time()
if current_time from 12:00 and 13:00:
    print("In time")
1

There are 1 answers

0
Martijn Pieters On BEST ANSWER

Compare against other datetime.time() objects:

if datetime.time(12) <= current_time <= datetime.time(13):

This uses comparison chaining, the above is basically the same expression as:

if datetime.time(12) <= current_time and current_time <= datetime.time(13):

but the current_time expression is evaluated just once.

I gave datetime.time() just the hour component; the minutes then default to 0:

>>> import datetime
>>> datetime.time(12)
datetime.time(12, 0)