想要动态创建选择字段,即之后的当前时间 + 30 分钟

Wants to create choice field dynamically i.e. current time after that + 30 min

我的代码如下:

def datetime_result():
    t = datetime.datetime.now()
    intervalTime = 30

    currenttime = t.minute

    checktm = int(currenttime) - int(intervalTime)

    if checktm < 0:
        addtime = abs(checktm)
    elif checktm > 0:
        addtime = intervalTime - checktm
    else:
        addtime = checktm

    opentime = t + datetime.timedelta(minutes=int(addtime))
    closetime = datetime.time(22, 30, 0)
    firsttime = opentime + datetime.timedelta(minutes=60)

    start_time = opentime.strftime('%H:%M')
    end_time = closetime.strftime('%H:%M')
    slot_time = 30

    # Start date from today to next 5 day
    start_date = datetime.datetime.now().date()
    end_date = datetime.datetime.now().date() + datetime.timedelta(days=0)

    days = []
    Delivery_Time_CHOICES = ""
    date = start_date
    while date <= end_date:
        time = datetime.datetime.strptime(start_time, '%H:%M')
        end = datetime.datetime.strptime(end_time, '%H:%M')
        while time <= end:
            Delivery_Time_CHOICES += ('(' + "'" + time.strftime("%I.%M%p")
                + "'" + ', ' + "'" + time.strftime("%I.%M%p") + "'" + '),')
            time += datetime.timedelta(minutes=slot_time)
        date += datetime.timedelta(days=1)
    return '(' + Delivery_Time_CHOICES + ')'

此代码将生成当前时间 + 病房时间 30 分钟的时间。当我在选择字段中调用此方法时,出现错误 "string index out of range" 并且当我将此方法的打印值直接放入选择字段变量中时,它会工作。

查看 dateutils.relativedelta 模块。

您可以轻松地操作日期时间对象,设置特定的小时、分钟秒值等。或者,您可以使用它根据需要 hours/minutes/seconds 等更改日期时间

from datetime import datetime
from dateutil.relativedelta import relativedelta

my_original_datetime = datetime.now()

minutes_offset = 30

opening_time = datetime.now() + relativedelta(minute=0, seconds=0, microsecond=0)
closing_time = datetime.now() + relativedelta(hour=17, minute=0, seconds=0, microsecond=0)

delivery_slot_start = opening_time
delivery_slot_end = delivery_slot_start + relativedelta(minutes=minutes_offset)

available_delivery_times = [(delivery_slot_start.strftime('%H:%M'), delivery_slot_end.strftime('%H:%M'))]

while delivery_slot_end <= closing_time:
    delivery_slot_start = delivery_slot_end
    delivery_slot_end += relativedelta(minutes=minutes_offset)
    available_delivery_times.append(
        (delivery_slot_start.strftime('%H:%M'), 
         delivery_slot_end.strftime('%H:%M'))
    )

print(tuple(available_delivery_times))