我有一个带商店运营时间的变量:
t = '08:00-17:00'
现在,我需要检查商店现在是否已打开:
from time import gmtime, strftime
print strftime("%H:%M", gmtime())
#11:26
最合适的方法是什么?作为旁注,我可以在几分钟内获得t
,或更方便的东西。
答案 0 :(得分:6)
而不是尝试将当前时间转换为字符串,而是应该str.split()
将t
分成两个不同的时间,然后使用datetime.datetime.time
将它们转换为datetime.datetime.strptime()
个对象,然后将其与datetime.datetime.now()
上的时间组件进行比较。示例 -
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
演示 -
关闭时间 -
>>> 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")
...
>>>
开放时间 -
>>> 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
>>>
使用此方法即使支持分钟,您也可以更改用于将time
转换为time
对象的格式,如果您愿意,还可以支持高达微秒。
答案 1 :(得分:0)
首先,您需要将 t 转换为可比较的值,例如整数,所以:
storeOpen, storeCloses = '08h00-17h00'.split('-')
这会将字符串'08h00-17h00'拆分为:
storeOpen => '08h00'
storeCloses => '17h00'
之后,您应该将 storeOpen 和 storeCloses 转换为整数:
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
然后你只是比较它们:
if (nowMinutes > storeOpenMinutes and nowHour > storeOpenHour) and (nowMinutes < storeCloseMinutes and nowHour < storeCloseHour):
println "is open!"