Instead of trying to convert the current time into string, you should rather str.split()
the t
into two different times, and then convert them into datetime.datetime.time
objects using datetime.datetime.strptime()
, and then compare that with the time component on datetime.datetime.now()
. Example -
import datetime
t = '08:00-17:00'
times = t.split('-')
start_time = datetime.datetime.strptime(times[0],'%H:%M').time()
end_time = datetime.datetime.strptime(times[1],'%H:%M').time()
if start_time <= datetime.datetime.now().time() <= end_time:
#Do you logic
Demo -
Closed time -
>>> import datetime
>>> t = '08:00-17:00'
>>> times = t.split('-')
>>> start_time = datetime.datetime.strptime(times[0],'%H:%M').time()
>>> end_time = datetime.datetime.strptime(times[1],'%H:%M').time()
>>> if start_time <= datetime.datetime.now().time() < end_time:
... print("Shop open")
...
>>>
Open time -
>>> t = '08:00-18:00'
>>> times = t.split('-')
>>> start_time = datetime.datetime.strptime(times[0],'%H:%M').time()
>>> end_time = datetime.datetime.strptime(times[1],'%H:%M').time()
>>> if start_time <= datetime.datetime.now().time() < end_time:
... print("Shop open")
...
Shop open
>>>
With this method even minutes are supported, you can change the format used to convert the time
to a time
object and support upto microseconds if you so wish.