使用Django模型中的start_time和end_time,如何在html页面中打印一系列时间

vbopmzt1  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(122)

我的模型是:

DAYS_OF_WEEK = (
    (0, 'Monday'),
    (1, 'Tuesday'),
    (2, 'Wednesday'),
    (3, 'Thursday'),
    (4, 'Friday'),
    (5, 'Saturday'),
    (6, 'Sunday'),
)

class Teacher(models.Model):
    name = models.CharField(max_length=64)
    start_time = models.TimeField(blank=False)
    end_time = models.TimeField(blank=False)
    day = models.IntegerField(choices=DAYS_OF_WEEK)

一个示例如下:莎莉十七点十八点
我想使用start_timeend_time以15分钟的间隔输出一个HTML页面,如下所示:

Sally
17:00
17:15
17:30
17:45
18:00
mjqavswn

mjqavswn1#

您可以定义函数minutes_slices()来准备您需要的时间列表,然后从Teacher示例中使用它,如Teacher.objects.get(pk=1).minutes_slices()

from datetime import date, datetime, timedelta

class Teacher(models.Model):
    name = models.CharField(max_length=64)
    start_time = models.TimeField(blank=False)
    end_time = models.TimeField(blank=False)
    day = models.IntegerField(choices=DAYS_OF_WEEK)

    def minutes_slices(self, minutes=15):
        # We can't add minutes to datetime.time, so we need to convert it to datetime
        start_date_time = datetime.combine(date.today(), self.start_time)
        end_date_time = datetime.combine(date.today(), self.end_time)
        next_time = start_date_time
        minutes_slices = [next_time.time()]
        if start_date_time < end_date_time:
            while next_time < end_date_time:
                next_time += timedelta(minutes=minutes)
                minutes_slices.append(next_time.time())
        return minutes_slices

如果需要格式化,可以将.strftime("%H:%M")添加到time()。

相关问题