diff --git a/CHANGES.md b/CHANGES.md index c62c0f6..2802382 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,8 @@ # Changelog +**11.5.2** (2024-10-15) + * Improved date determination of `get_start_and_end_date_from_calendar_week` + **11.5.1** (2024-10-08) * Added Python 3.13 support * Added Djade linter to pre-commit diff --git a/ambient_toolbox/__init__.py b/ambient_toolbox/__init__.py index 345046a..5e694d0 100644 --- a/ambient_toolbox/__init__.py +++ b/ambient_toolbox/__init__.py @@ -1,3 +1,3 @@ """Python toolbox of Ambient Digital containing an abundance of useful tools and gadgets.""" -__version__ = "11.5.1" +__version__ = "11.5.2" diff --git a/ambient_toolbox/utils/date.py b/ambient_toolbox/utils/date.py index 7f29bbf..297e766 100644 --- a/ambient_toolbox/utils/date.py +++ b/ambient_toolbox/utils/date.py @@ -94,8 +94,20 @@ def get_start_and_end_date_from_calendar_week(year: int, calendar_week: int) -> """ Returns the first and last day of a given calendar week """ - monday = datetime.datetime.strptime(f"{year}-{calendar_week}-1", "%Y-%W-%w").astimezone().date() - return monday, monday + datetime.timedelta(days=6.9) + start_of_week = datetime.datetime.strptime(f"{year}-{calendar_week}-1", "%Y-%W-%w").astimezone().date() + + if calendar_week == 1: + # Calculating first_day_of_week for calendar_week == 1 is always tricky, as the first calendar week + # can actually start in the n-1 year. The above .strptime() can not handle this however, and would always + # return the first of January. + # For this case, we consider the fourth of january, as it will _always_ be in the first calendar week + # (see: https://en.wikipedia.org/wiki/ISO_week_date#First_week) + + fourth_of_january = datetime.date(year=year, month=1, day=4) + + start_of_week = fourth_of_january - relativedelta(days=fourth_of_january.weekday()) + + return start_of_week, start_of_week + relativedelta(days=6) def get_next_calendar_week(compare_date: datetime.date) -> int: diff --git a/tests/test_utils_date.py b/tests/test_utils_date.py index e6dfc36..c2ca206 100644 --- a/tests/test_utils_date.py +++ b/tests/test_utils_date.py @@ -38,6 +38,10 @@ def test_get_start_and_end_date_from_calendar_week(self): self.assertEqual(monday, datetime.date(year=2018, month=1, day=1)) self.assertEqual(sunday, datetime.date(year=2018, month=1, day=7)) + monday, sunday = get_start_and_end_date_from_calendar_week(2020, 1) + self.assertEqual(monday, datetime.date(year=2019, month=12, day=30)) + self.assertEqual(sunday, datetime.date(year=2020, month=1, day=5)) + monday, sunday = get_start_and_end_date_from_calendar_week(2017, 30) self.assertEqual(monday, datetime.date(year=2017, month=7, day=24)) self.assertEqual(sunday, datetime.date(year=2017, month=7, day=30))