Home > Enterprise >  With start_time and end_time in Django models, how to print a series of times in an html page
With start_time and end_time in Django models, how to print a series of times in an html page

Time:12-09

My model is:

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)

One instance would be like: Sally 17:00 18:00 0

I want to output an HTML page using start_time and end_time in an 15-minute interval, something like this:

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

CodePudding user response:

You can define function minutes_slices() to prepare list of time you need, and then use it from Teacher instance like 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().strftime("%H:%M")]
        if start_date_time < end_date_time:
            while next_time < end_date_time:
                next_time  = timedelta(minutes=minutes)
                minutes_slices.append(next_time.time().strftime("%H:%M"))
        return minutes_slices
    
  • Related