Reputation: 21
I am fairly new to Python. I am trying to determine if a store is open or closed based on 24 hour format. If the store hours (open - close) are 06:00:00 - 22:00:00 then there is not problem with the below code If the store hours are 06:00:00 - 03:00:00, then I am having trouble figuring out how to calculate it so that both scenarios work.
Any help is greatly appreciated. Thanks!
gs_StoreOpenHours24 = '06:00:00, 03:00:00'
tnow = datetime.now().time() #07:54:10.390955
print('tnow:' + str(tnow))
#Get the store open/close values
StoreOpen, StoreClose = gs_StoreOpenHours24.split(',')
StoreOpen = StoreOpen.strip()
StoreClose = StoreClose.strip()
#Format the store open/close to a time format
StoreOpen = datetime.strptime(StoreOpen, '%H:%M:%S').time() #convert to a time format. 06:00:00
StoreClose = datetime.strptime(StoreClose, '%H:%M:%S').time() #convert to a time format. #22:00:00
print('StoreOpen:' + str(StoreOpen))
print('StoreClose:' + str(StoreClose))
#check if the store is open or closed
# if (tnow <= StoreOpen and tnow >= StoreClose) :
if (StoreOpen <= tnow and StoreClose >= tnow):
print('Store Is Open')
else:
print('Store Is Closed')
Upvotes: 0
Views: 244
Reputation: 186
We know that close is always after open, so you could check if the parsed close time is after the parsed open time and if not just add a day to close time.
StoreOpen = datetime.strptime(StoreOpen, '%H:%M:%S').time() #convert to a time format. 06:00:00
StoreClose = datetime.strptime(StoreClose, '%H:%M:%S').time() #convert to a time format. #22:00:00
if StoreOpen > StoreClose:
StoreClose += datetime.timedelta(days=1)
Upvotes: 1