Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python calendar.HTMLCalendar

I think I want to use pythons built in calendar module to create an HTML calendar with data. I say I think because I'll probably think of a better way, but right now it's a little personal. I don't know if this was intended to be used this way but it seems like it is a little pointless if you can't at least making the days into a <a hrefs>.

This sets up a calendar for this month with Sunday as the first day.

import calendar
myCal = calendar.HTMLCalendar(calendar.SUNDAY)
print myCal.formatmonth(2009, 7)

it prints

<table border="0" cellpadding="0" cellspacing="0" class="month">\n<tr>
<th colspan="7" class="month">July 2009</th></tr>\n<tr><th class="sun">Sun</th>
<th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th>
<th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th></tr>\n
<tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td>
<td class="noday">&nbsp;</td><td class="wed">1</td><td class="thu">2</td><td class="fri">3</td>
<td class="sat">4</td></tr>\n<tr><td class="sun">5</td><td class="mon">6</td><td class="tue">7</td>
<td class="wed">8</td><td class="thu">9</td><td class="fri">10</td>
<td class="sat">11</td></tr>\n<tr><td class="sun">12</td><td class="mon">13</td>
<td class="tue">14</td><td class="wed">15</td><td class="thu">16</td><td class="fri">17</td>
<td class="sat">18</td></tr>\n<tr><td class="sun">19</td><td class="mon">20</td>
<td class="tue">21</td><td class="wed">22</td><td class="thu">23</td><td class="fri">24</td>
<td class="sat">25</td></tr>\n<tr><td class="sun">26</td><td class="mon">27</td>
<td class="tue">28</td><td class="wed">29</td><td class="thu">30</td><td class="fri">31</td>
<td class="noday">&nbsp;</td></tr>\n</table>\n

I would like to insert some data into the HTMLCalendar object before it renders the html string. I just can't figure out how.

For example

<td class="tue">28<br />[my data]</td>
like image 628
Kenny Pyatt Avatar asked Jul 09 '09 02:07

Kenny Pyatt


1 Answers

Create a new class inheriting from HTMLCalendar. Override the formatday method.

Whoever makes comments like "this library is useless" obviously doesn't understand Python.

class EmployeeScheduleCalendar(HTMLCalendar):
    def formatday(self, day, weekday):
        """
          Return a day as a table cell.
        """
        if day == 0:
            return '<td class="noday">&nbsp;</td>' # day outside month
        else:
            return '<td class="%s"><a href="%s">%d</a></td>' % (self.cssclasses[weekday], weekday, day)
like image 136
Alan Hynes Avatar answered Oct 02 '22 00:10

Alan Hynes