time_ranges = ['Sunday-Thursday: 5:00 pm - 8:00 pm', 'Friday - Saturday: 1:00 pm - 2:00 pm']
有没有一种简单的方法可以将上面显示的字符串列表转换为日期时间范围?是否有一个可以轻松完成此任务的包或库?
答案 0 :(得分:0)
以下是使用营业时间列表进行此操作的一种方法:
import datetime
Now = datetime.datetime.now()
business_hours = [(8,18),(8,18),(12,18),(8,18),(8,20),(8,20),(-1,-1)]
for i in range(6):
Now = datetime.datetime.now() + datetime.timedelta(days=i)
if Now.hour >= business_hours[Now.weekday()][0]\
and Now.hour <= business_hours[Now.weekday()][1]:
print Now.strftime("%a %d-%m-%Y"), "The store is open"
else:
print Now.strftime("%a %d-%m-%Y"), "The Store is closed"
结果:
Sun 13-12-2015 The Store is closed
Mon 14-12-2015 The store is open
Tue 15-12-2015 The store is open
Wed 16-12-2015 The Store is closed
Thu 17-12-2015 The store is open
Fri 18-12-2015 The store is open
显然,此示例尝试使用多个日期证明这一点,出于您的目的,您将转储for range
循环并仅测试Now
。
请注意weekday
和isoweekday
之间的区别,它区分星期一或星期日的第一天,不同的是weekday
,其中星期一为0,星期日为6,isoweekday
星期一是1,星期日是7