Last active
August 1, 2025 01:22
-
-
Save yeiichi/8a1e256ef3a034e1f0c290ed82e70bc9 to your computer and use it in GitHub Desktop.
Determine the nth week of the month for a given date string.
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
| #!/usr/bin/env python3 | |
| import calendar | |
| from datetime import date | |
| import numpy as np | |
| def ordinal(n): | |
| """Converts an integer to its ordinal representation. | |
| Reference: | |
| https://stackoverflow.com/a/16671271/11042987 | |
| """ | |
| return str(n) + ( | |
| "th" if 4 <= n % 100 <= 20 | |
| else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")) | |
| class DateAttrs: | |
| def __init__(self, date_string): | |
| self.my_date = date.fromisoformat(date_string) if date_string else date.today() | |
| self.yr = self.my_date.year | |
| self.mo = self.my_date.month | |
| self.dy = self.my_date.day | |
| self.dow = self.my_date.strftime('%a') | |
| self.wk_num = self.my_date.isocalendar().week | |
| self.wk_day = self.my_date.isocalendar().weekday | |
| def determine_nth_wk_of_month(self): | |
| # Calendar array | |
| arr = np.array(calendar.monthcalendar(self.yr, self.mo)) | |
| # Find the row number and convert it to nth week of the month. | |
| return np.argwhere(arr == self.dy)[0, 0] + 1 # Add 1 for 1-based indexing. | |
| def display_calendar_with_comments(self): | |
| print(f'''\033[93m{self.dow}, {self.my_date.isoformat()} is | |
| the {ordinal(self.determine_nth_wk_of_month())} week of the month. | |
| the {ordinal(self.wk_num)} week of the year\033[0m | |
| See the calendar below:\n''') | |
| print(calendar.month(self.yr, self.mo)) | |
| def set_week_start(start_day): | |
| """Sets the starting day of the week for the calendar module. | |
| Args: | |
| start_day (str): A string representing the desired starting day. | |
| """ | |
| # noinspection PyCompatibility | |
| match start_day.lower(): | |
| case 'sat': | |
| calendar.setfirstweekday(calendar.SATURDAY) | |
| case 'sun': | |
| calendar.setfirstweekday(calendar.SUNDAY) | |
| case _: | |
| calendar.setfirstweekday(calendar.MONDAY) | |
| if __name__ == '__main__': | |
| set_week_start(input('First day of the week? (Mon, Sat, Sun; default: Mon) >> ')) | |
| my_instance = DateAttrs(input('Date? [yyyy-mm-dd] >> ')) | |
| my_instance.display_calendar_with_comments() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment