我有一个tuple列表,每次间隔15分钟,持续24小时。现在我需要在工作时间之外删除时间。
我的时代:
times = []
for i in range(0, 24 * 4):
times.append((datetime.combine(date.today(), time()) + timedelta(minutes=15) * i).time())
营业时间:
time_open = '08:00:00'
time_close = '17:00:00'
如何在营业时间之外从列表中删除时间?
答案 0 :(得分:1)
如果我明白你想要什么,这是一个快速而肮脏的解决方案。您可以在追加到列表之前检查业务开放/关闭时间之间的时间。
from datetime import datetime as d, timedelta, time
import datetime as o_d
time_open = '08:00:00'
time_close = '17:00:00'
times = []
for i in range(0, 24 * 4):
date = (d.combine(o_d.date.today(), time()) + timedelta(minutes=15) * i).time()
date_str = date.strftime("%H:%M:%S")
if time_open <= date_str <= time_close:
times.append(date_str)
#times.append(date)
print(times)
根据评论进行编辑:如果您想要一个通常称为“军事”时间的元组表示,而不是大多数人习惯的时间,即上午/下午,您可以执行以下操作
from datetime import datetime as d, timedelta, time
import datetime as o_d
time_open = '08:00:00'
time_close = '17:00:00'
times = []
for i in range(0, 24 * 4):
date = (d.combine(o_d.date.today(), time()) + timedelta(minutes=15) * i).time()
date_str = date.strftime("%H:%M:%S")
if time_open <= date_str <= time_close:
#If you want a list of just standard times
#times.append(date_str)
#If you want the time representation(s) here and no longer need the
#the datetime object
times.append((date_str, date.strftime("%I:%M %p"))
#If you still need the datetime object append this do list comprehension below in comment with #options = ....
#times.append(date)
print(times)
#assuming you have appended date above see comment
#options = [( c.strftime("%H:%M:%S"), c.strftime("%I:%M %p")) for c in times]