/home/alex/dev/calendar.py (1)

From RaySoft
#!/usr/bin/env python3
# ------------------------------------------------------------------------------
# calendar.py
# ===========
#
# Scope     Native
# Copyright (C) 2024 by RaySoft, Zurich, Switzerland
# License   GNU General Public License (GPL) 2.0
#           https://www.gnu.org/licenses/gpl2.txt
#
# ------------------------------------------------------------------------------

WEEKDAY_NAMES = 'Mo Tu We Th Fr Sa Su'

# ------------------------------------------------------------------------------

from datetime import date, timedelta
from sys import exit

# ------------------------------------------------------------------------------

def main():
    # Get the current date
    # date_today = date(2005, 1, 1)     # Debug date: calendar week is 53
    # date_today = date(2008, 12, 29)   # Debug date: calendar week is 1
    date_today = date.today()

    # Get the day of week of the first day of the current month
    first_weekday = date(date_today.year, date_today.month, 1) \
                    .isocalendar()[2]

    # Get the date of the last day of the current month
    if date_today.month != 12:
        last_month_day = date(date_today.year, date_today.month + 1, 1) \
                         - timedelta(days=1)
    else:
        last_month_day = date(date_today.year, 12, 31)

    # Get the week numbers for the current month
    weeks = []

    for day in range(1, last_month_day.day + 1):
        week = date(date_today.year, date_today.month, day).isocalendar()[1]

        if week not in weeks:
            weeks.append(week)

    for week in weeks:
        print(f'Week {week:<18d}', end='')

    print()

    print(f'{WEEKDAY_NAMES:<23s}' * len(weeks))

    print('   ' * (first_weekday - 1), end='')

    for day in range(1, last_month_day.day + 1):
        if date_today.day == day:
            print(f'\033[1;31m{day:<3d}\033[0m', end='')
        else:
            print(f'{day:<3d}', end='')

        if (day + first_weekday - 1) % 7 == 0:
            print('  ', end='')

    print()

    return 0

# ------------------------------------------------------------------------------

if __name__ == '__main__':
    return_value = main()

    exit(return_value)

Usage

~/dev/calendar.py

Output:

Week 52                Week 1                 Week 2                 Week 3   ...
Mo Tu We Th Fr Sa Su   Mo Tu We Th Fr Sa Su   Mo Tu We Th Fr Sa Su   Mo Tu We ...
                  1    2  3  4  5  6  7  8    9  10 11 12 13 14 15   16 17 18 ...