Skip to content

Instantly share code, notes, and snippets.

@klement97
Last active August 7, 2021 21:07
Show Gist options
  • Save klement97/0912e56a8023741e87201fac0da261cd to your computer and use it in GitHub Desktop.
Save klement97/0912e56a8023741e87201fac0da261cd to your computer and use it in GitHub Desktop.
A function to get the week number and a tester function for it.
import calendar
import datetime
from math import ceil
def get_week_number(date: datetime.date) -> int:
"""
Credits goes to:https://stackoverflow.com/a/66176965/9309611
"""
return (date.day - 1 + (date.weekday() - date.day + 1) % 7) // 7 + 1
def test_get_week_number():
for year in range(datetime.date.min.year, datetime.date.max.year + 1):
for month in range(1, 12 + 1):
month_days = calendar.monthcalendar(year, month)
for week_number in range(1, len(month_days) + 1):
for weekday in range(7):
day = month_days[week_number - 1][weekday]
if day == 0:
continue
date = datetime.date(year, month, day)
assert week_number == get_week_number(date), \
f'{date} week from calendar: {week_number},' \
f' from function: {get_week_number(date)}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment