Monatskalender für LaTeX mit Python erzeugen

Hier ein Beispiel, wie man mit Python kleine Monatskalender erzeugen kann. Geht auch mit LaTeX allein, ich möchte aber verschiedene Output-Formate (Markdown, HTML, etc.) erzeugen und dabei die komplette Kontrolle über den Code behalten.

# -*- coding: utf-8 -*-
 
import calendar
import datetime
 
def number_of_weeks(year, month):
    """
        Returns a tupel with the ISO no of the first and week and the no of weeks
    """
    tup_month_days = calendar.monthrange(year, month)
    first = datetime.date(year, month, 1)
    last = datetime.date(year, month, tup_month_days[1])
    first_week = first.isocalendar()[1]
    last_week = last.isocalendar()[1]
    return (first_week, last_week, last_week-first_week+1)
 
def gen_cal_latex(year, month):
    """
        https://stackoverflow.com/questions/9459337/assign-value-to-an-individual-cell-in-a-two-dimensional-python-array
    """
    c = calendar.TextCalendar()
    week_month_first, week_month_last, no_of_weeks = number_of_weeks(year, month)
 
    # generate calendar list, using tupel as a key    
    m = {(i, j):' ' for i in range(no_of_weeks) for j in range(7)}
 
    for tupel_date in c.itermonthdays4(year, month):
        t_year, t_month, t_day, t_weekday = tupel_date
        # use only dates inside the required month
        if t_month == month:
            temp_date = datetime.date(t_year, t_month, t_day)
            # check in which week we are with the current date
            # to get index for the list
            week_no = temp_date.isocalendar()[1]
            m[week_no % week_month_first, t_weekday] = t_day
 
    print(r'\begin{tabular}{rrrrrrr}')
    print(r'Mo & Di & Mi & Do & Fr & Sa & So \\')
    for i in m:
        if i[1] < 6:
            print('{0} &'.format(m[i]), end='')
        else:
            print('{0}'.format(m[i]),end='')
        if i[1] == 6:
            print(r'\\')
    print(r'\end{tabular}')
 
gen_cal_latex(2020, 4)

Erzeugt werden kleine Monatskalender der Form

\begin{tabular}{rrrrrrr}
Mo & Di & Mi & Do & Fr & Sa & So \\
  &  &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 &  &  & \\
\end{tabular}

Per Copy & Paste kann man den Code in ein LaTeX-Dokument kopieren, natürlich lässt sich das alles auch direkt in eine LaTeX-Datei schreiben.

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website