2

I have a variable with the operating time of a store:

t = '08:00-17:00'

Now, i need to check if the store is open now:

from time import gmtime, strftime
print strftime("%H:%M", gmtime())
#11:26

What is the most adequate way to make this? As side note, i can have t in minutes, or something more convenient.

user2990084
  • 2,699
  • 9
  • 31
  • 46

2 Answers2

6

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.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
0

First, you need to convert the t to a comparable value, such as a integer, so:

storeOpen, storeCloses = '08h00-17h00'.split('-')

This will split the string '08h00-17h00' into:

storeOpen => '08h00'
storeCloses => '17h00'

After that, you should transform the storeOpen and storeCloses into integer:

storeOpenHour, storeOpenMinutes = storeOpen.split('h') #splits the storeOpen into two
#converts to integer
storeOpenHour = int(storeOpenHour)
storeOpenMinutes = int(storeOpenMinutes)
#you should repeat the same process to storeClose

And then you just compare them:

if (nowMinutes > storeOpenMinutes and nowHour > storeOpenHour) and (nowMinutes < storeCloseMinutes and nowHour < storeCloseHour):
    println "is open!"
Pedro N
  • 1
  • 1