【问题标题】:Calculate 24 hour time to determine store open/store close计算 24 小时时间以确定开店/关店
【发布时间】:2020-03-12 04:04:01
【问题描述】:

我对 Python 还很陌生。我正在尝试根据 24 小时格式确定商店是营业还是关闭。 如果商店营业时间(开 - 关)是 06:00:00 - 22:00:00 那么下面的代码没有问题 如果商店营业时间是 06:00:00 - 03:00:00,那么我很难弄清楚如何计算它,以便两种情况都有效。

非常感谢任何帮助。谢谢!

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

【问题讨论】:

  • 变量和函数名一般应遵循lower_case_with_underscores风格。

标签: python datetime


【解决方案1】:

我们知道关闭总是在打开之后,因此您可以检查解析的关闭时间是否在解析的打开时间之后,如果不是,则添加一天的关闭时间。

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)

【讨论】:

  • 啊。谢谢!
猜你喜欢
  • 2016-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多