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



我的模型是:

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)

一个例子是:Sally 17:00 18:00

我想在15分钟的时间间隔内使用start_timeend_time输出一个HTML页面,如下所示:

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

您可以定义函数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")添加到时间()中。

相关内容

  • 没有找到相关文章

最新更新