简体   繁体   中英

How to check if current time is between a certain time period?

I am trying to check if the current time is between a certain time period,in this case between 10:00pm to 11:00pm but running into below error,any guidance on how to fix this?

import datetime
current_time = datetime.datetime.now().time()

if '22:00' <= current_time <= '23:00':
    print "current time is between 10:00pm to 11:00pm"
else:
    print "current time is NOT between 10:00pm to 11:00pm"

Error:-

Traceback (most recent call last):
  File "datetime_script.py", line 4, in <module>
    if '22:00' <= current_time <= '23:00':
TypeError: can't compare datetime.time to str

Access the hour field using current_time.hour which returns an int which implies that it should not be compared with str .

You can do therefore:

import datetime
current_time = datetime.datetime.now().time()

if 22<= current_time.hour <=23:
    print ("current time is between 10:00pm to 11:00pm")
else:
    print ("current time is NOT between 10:00pm to 11:00pm")

This will work. Just convert it to string.

import datetime
current_time = datetime.datetime.now().time()
# use the str function
if '22:00' <= str(current_time) <= '23:00':
    print ("current time is between 10:00pm to 11:00pm")
else:
    print ("current time is NOT between 10:00pm to 11:00pm")

You can use the fact that Python lets you do arithmetic and comparisons with datetime objects. You appear only to be concerned about hours and minutes, so just get these from the current time to create a datetime.time object, and compare these with similar objects denoting 22:00h and 23:00h.

import datetime
current_time = datetime.datetime.now()
now = datetime.time(current_time.hour, current_time.minute)
if datetime.time(22, 0) <= now <= datetime.time(23, 0):
    print "current time is between 10:00pm to 11:00pm":
else:
    print "current time is NOT between 10:00pm to 11:00pm"

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