Created
February 6, 2024 22:06
-
-
Save dalepotter/c9a6a507c540bf1162b8e95ba725542d to your computer and use it in GitHub Desktop.
Output calendar for a given month with weekdays only. Useful for adding to invoices.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Output calendar for a given month showing: | |
# - Weekdays only | |
# - Zero padded single digit day numbers | |
# | |
# Example usage: | |
# $ python weekday_calendar.py | |
# Enter month (1 = January, 12 = December) [2]: | |
# Enter year [2024]: | |
# February 2024 | |
# Mon Tue Wed Thu Fri | |
# 01 02 | |
# 05 06 07 08 09 | |
# 12 13 14 15 16 | |
# 19 20 21 22 23 | |
# 26 27 28 29 | |
from calendar import TextCalendar | |
from datetime import date | |
class WeekdayTextCalendar(TextCalendar): | |
VALID_WEEKDAY_NUMS = range(0, 5) # Represents Monday (0) to Friday (4). | |
def formatday(self, day, weekday, width): | |
""" | |
Returns a formatted day (with zero padded single digits). | |
""" | |
if day == 0: | |
s = '' | |
elif weekday not in self.VALID_WEEKDAY_NUMS: | |
s = '' | |
else: | |
s = str(day).zfill(2) # Zero pad single-digit days | |
return s.center(width) | |
def formatweekheader(self, width): | |
""" | |
Return a header for a week (weekdays only). | |
""" | |
return ' '.join(self.formatweekday(i, width) for i in self.iterweekdays() if i in self.VALID_WEEKDAY_NUMS) | |
def formatmonth(self, theyear, themonth, w=0, l=0): | |
""" | |
Return a month's calendar string (multi-line). | |
""" | |
w = max(2, w) | |
l = max(1, l) | |
s = self.formatmonthname(theyear, themonth, len(self.VALID_WEEKDAY_NUMS) * (w + 1) - 1) | |
s = s.rstrip() | |
s += '\n' * l | |
s += self.formatweekheader(w).rstrip() | |
s += '\n' * l | |
for week in self.monthdays2calendar(theyear, themonth): | |
s += self.formatweek(week, w).rstrip() | |
s += '\n' * l | |
return s | |
current_month = date.today().month | |
current_year = date.today().year | |
month = int(input(f"Enter month (1 = January, 12 = December) [{current_month}]: ") or current_month) | |
year = int(input(f"Enter year [{current_year}]: ") or current_year) | |
WeekdayTextCalendar().prmonth(year, month, w=4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment