使用datetime模块设置时间间隔

时间:2015-08-10 21:04:20

标签: python datetime

我正在尝试编写一个程序,允许用户从一周中可用天数列表中选择约会时间。我需要有关如何使用datetime模块来完成此操作的帮助,而不是我想出的内容。

avail_days = {'Mon': ['8:00AM', '8:30AM', '9:00AM', '10:00AM', '10:30AM', '11:00AM', '11:30AM', '12:00AM'], 'Tues': ['8:00AM', '8:30AM', '9:00AM', '10:00AM', '10:30AM', '11:00AM', '11:30AM', '12:00AM']}

每次约会应持续30分钟,可用日期应为工作日上午8点至中午12点。

1 个答案:

答案 0 :(得分:0)

说到日期范围,我发现Delorean包,它的stops()功能非常有用,可读且方便。假设您希望以编程方式为两个日期时间之间的每一天生成时间范围,以下是一个示例实现:

from datetime import datetime, timedelta

from delorean import stops
import delorean

start = datetime.today()
stop = datetime.today() + timedelta(7)

for day in stops(freq=delorean.DAILY, start=start, stop=stop):
    start = day.naive().replace(hour=8, minute=0)
    stop = day.naive().replace(hour=12, minute=0)

    for t in stops(freq=delorean.MINUTELY, interval=30, start=start, stop=stop):
        print t.datetime.strftime("%A %H:%M")

打印:

Monday 08:00
Monday 08:30
Monday 09:00
Monday 09:30
Monday 10:00
Monday 10:30
Monday 11:00
Monday 11:30
Monday 12:00
Tuesday 08:00
Tuesday 08:30
Tuesday 09:00
Tuesday 09:30
Tuesday 10:00
Tuesday 10:30
Tuesday 11:00
Tuesday 11:30
Tuesday 12:00
Wednesday 08:00
Wednesday 08:30
Wednesday 09:00
Wednesday 09:30
Wednesday 10:00
Wednesday 10:30
Wednesday 11:00
Wednesday 11:30
Wednesday 12:00
...
Sunday 08:00
Sunday 08:30
Sunday 09:00
Sunday 09:30
Sunday 10:00
Sunday 10:30
Sunday 11:00
Sunday 11:30
Sunday 12:00
Monday 08:00
Monday 08:30
Monday 09:00
Monday 09:30
Monday 10:00
Monday 10:30
Monday 11:00
Monday 11:30
Monday 12:00