对于体育馆的日程安排,我需要创建一个模型,使用该模型我将获得一份七天的姓名列表。该列表将每天更新,因此首先始终是星期几。列表每天都会转移到一天,例如,在今天“星期三”一词所代表的单元格中,明天将出现“星期四”一词,后天将出现“星期五”等。然后,应该将日期的名称检索到视图中并传递给模板。
我试图这样做:
import calendar
import datetime
from datetime import *
from django.db import models
from django.utils.translation import ugettext as _
class DayOfWeekSchedule(models.Model):
"""General dynamic schedule for a week"""
DOW_CHOICES = (
(1, _("Monday")),
(2, _("Tuesday")),
(3, _("Wednesday")),
(4, _("Thursday")),
(5, _("Friday")),
(6, _("Saturday")),
(7, _("Sunday")),
)
day_of_week = models.PositiveSmallIntegerField(
choices=DOW_CHOICES,
verbose_name=_('Day of week')
)
def days_of_week(self):
my_date = date.today()
current_day_name = calendar.day_name[my_date.weekday()]
index1 = DOW_CHOICES.index(current_day_name) #from Monday=0 (i.e. Friday=4)
list_daynames = list(DOW_CHOICES[index1:] + DOW_CHOICES)[:7] #list of names, current is first
list_index = (2, 3, 4, 5, 6, 7, 1) #to compensate systems difference
list2 = list(list_index[index1:] + list_index)[:7]
context_days = dict(zip(list_keys, list_daynames))
return context_days
但是
DOW_CHOICES.index (current_day_name)
和
list_daynames = list (DOW_CHOICES [index1:] + DOW_CHOICES) [: 7]
不能正常工作,因为.index()不适用于这种类型的元组。
我不知道该怎么做。
答案 0 :(得分:0)
也许您想得太多了。如果我正确理解了您想要的内容,则可以执行以下操作:
from datetime import datetime, timedelta
days = {
'1': _('Monday'),
'2': _('Tuesday'),
'3': _('Wednesday'),
'4': _('Thursday'),
'5': _('Friday'),
'6': _('Saturday'),
'7': _('Sunday')
}
DOW_CHOICES = []
today = datetime.today()
for i in range(7):
day_number = (today + timedelta(days=i)).isoweekday()
day = days[str(day_number)]
DOW_CHOICES.append((day_number, day))
这将获取今天的日期,并创建一个包含日期和日期的元组列表。结果将是:
[
(3, 'Wednesday'),
(4, 'Thursday'),
(5, 'Friday'),
(6, 'Saturday'),
(7, 'Sunday'),
(1, 'Monday'),
(2, 'Tuesday')
]