使用djang构建html日历视图

2024-10-01 13:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用django构建一个日历视图,并试图避免在视图中写入任何html标记。我找到了一个能帮我到达目的地的密码

from datetime import date, datetime, timedelta, time
import calendar

year=2011
month=12
change=None

# init variables
cal = calendar.Calendar()
month_days = cal.itermonthdays(year, month)
lst = [[]]
week = 0

# make month lists containing list of days for each week
# each day tuple will contain list of entries and 'current' indicator
for day in month_days:
    lst[week].append((day))
    if len(lst[week]) == 7:
        lst.append([])
        week += 1

在我看来,我做到了以下几点

^{pr2}$

现在,上面的代码正在按月份和年份参数打印日历,但它们出现错误。当我用2011年12月与日历比较时,一个月的第一天从星期四开始,而在日历中它从星期三开始。谁能帮我指出我做错了什么吗?在

更新

看来问题是从这个月开始的。我试着做以下事情

>>> month_days = cal.itermonthdays(2011, 12)
>>> for day in month_days:
...  print day
... 
0
0
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
0

我不知道我是应该改变某种a设置还是以不同的方式启动这个类。但是,根据我的个人电脑日历,输出应该以4个零开始,以无结尾。它显示2011年12月开始于一个星期四,也就是一周的第五天,因此在开始计数之前应该有4个零。嗯,有什么建议可以帮我解决这个问题吗?在


Tags: ofimport视图fordatetimedaysyearcalendar
3条回答

When I compare it with the calendar, using december 2011, the first day of the month starts at thursday while in calendar its starting on wednesday. can anyone help point out what I did wrong here?

我有一个坏消息要告诉你,根据我的windows日历,2011年12月的第一天是星期四

你需要包括

cal.setfirstweekday(6)

以前

^{pr2}$

根据python documentation。。。在

By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention).

在我看来,你的问题只是itermonthdays从星期一开始,而不是星期天。您可以通过临时替换来确认这一点

itermonthdays

^{pr2}$

以及

lst[week].append(day)

lst[week].append(day.strftime("%A")))

这将临时用星期名称替换日期编号。在

编辑:问题的一个可能的解决方案是将lst初始化为[[0]],然后在循环的末尾设置{}。在

相关问题 更多 >