我正在研究简单的任务管理工具。 我需要生成下拉列表,以15分钟的间隔显示两个特定小时之间的可用时间段,例如
(输入) 13:00 - 14:00 (输出)13:15,13:30,13:45,15:00
(输入) 10:00 - 13:00 (输出)10:00,10:15,10:30 ...... 13:00
实现这一目标的最简单的解决方案是什么?
答案 0 :(得分:2)
创建一个简单的生成器:
import datetime
def time_slots(start_time, end_time):
t = start_time
while t <= end_time:
yield t.strftime('%H:%M')
t = (datetime.datetime.combine(datetime.date.today(), t) +
datetime.timedelta(minutes=15)).time()
使用它是这样的:
>>> import datetime
>>> start_time = datetime.time(13, 00)
>>> end_time = datetime.time(14, 00)
>>> list(time_slots(start_time, end_time))
['13:00', '13:15', '13:30', '13:45', '14:00']
>>>
答案 1 :(得分:0)
试试这个:
>>> from datetime import date, datetime, timedelta
>>> beginning = datetime.strptime("10:00", "%H:%M")
>>> hours = 1
>>> times = [beginning + timedelta(minutes=x) for x in range(15, (60 * hours) + 15, 15)]
>>> times
[datetime.datetime(1900, 1, 1, 10, 15), datetime.datetime(1900, 1, 1, 10, 30), datetime.datetime(1900, 1, 1, 10, 45), datetime.datetime(1900, 1, 1, 11, 0)]