user3508811
user3508811

Reputation: 925

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

Upvotes: 1

Views: 1328

Answers (3)

teraspora
teraspora

Reputation: 462

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"

Upvotes: 1

ansev
ansev

Reputation: 30930

Access the hour field using current_time.hour which returns anint 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")

Upvotes: 1

Sammit
Sammit

Reputation: 169

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")

Upvotes: 0

Related Questions