Python查找时隙

2024-04-20 14:04:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个小Python脚本,根据日历约会查找可用的时间段。我可以在这里重用帖子中的代码:(Python - Algorithm find time slots)。在

对于一个小时或更长时间的预约,它似乎确实有效,但对于那些不到一个小时的预约,它似乎无法赶上。换言之,它显示的时间段是可用的,即使预约已被预订(少于一小时)。在

下面的示例代码来自帖子提到的,有我自己的值“小时”和“约会”。在

#get_timeslots.py

from datetime import datetime, timedelta

appointments = [(datetime.datetime(2017, 9, 7, 9, 30), 
               datetime.datetime(2017, 9, 7, 12, 30), 
               datetime.datetime(2017, 9, 7, 13, 30), 
               datetime.datetime(2017, 9, 7, 14, 0))]

hours = (datetime.datetime(2017, 9, 7, 6, 0), datetime.datetime(2017, 9, 7, 23, 0))


def get_slots(hours, appointments, duration=timedelta(hours=1)):
    slots = sorted([(hours[0], hours[0])] + appointments + [(hours[1], hours[1])])
    for start, end in ((slots[i][1], slots[i+1][0]) for i in range(len(slots)-1)):
        assert start <= end, "Cannot attend all appointments"
        while start + duration <= end:
            print "{:%H:%M} - {:%H:%M}".format(start, start + duration)
            start += duration

if __name__ == "__main__":
    get_slots(hours, appointments)

当我运行脚本时,我得到:

^{pr2}$

问题是,虽然9:30-12:30的第一个约会被阻止,并且没有出现在可用的时段中,但是后来的13:30-2:00的约会没有被阻止,因此在时间段输出中显示为可用。(见“13:30-14:30”)。在

我是一个Python新手,承认我在没有完全理解的情况下回收了代码。有人能告诉我该换些什么,让它在不到一个小时的时间内把预约安排好?在

TIA公司

-克里斯


Tags: 代码脚本getdatetimestart帖子timedeltaend
1条回答
网友
1楼 · 发布于 2024-04-20 14:04:32

你错过了约会中的括号。试试这个:

#from datetime import datetime, timedelta
import datetime

#notice the additional brackets to keep the 2 slots as two separate lists. So, 930-1230 is one slot, 1330-1400 is an another.

appointments = [(datetime.datetime(2017, 9, 7, 9, 30), 
           datetime.datetime(2017, 9, 7, 12, 30)), 
           (datetime.datetime(2017, 9, 7, 13, 30), 
           datetime.datetime(2017, 9, 7, 14, 0))]

相关问题 更多 >