diff --git a/python_carbon/__init__.py b/python_carbon/__init__.py index 19d608e..c610f93 100644 --- a/python_carbon/__init__.py +++ b/python_carbon/__init__.py @@ -561,8 +561,10 @@ def endOfDay(self) -> 'Carbon': ) def startOfWeek(self) -> 'Carbon': + start_of_week = self._date - timedelta(days=self._date.weekday()) + return Carbon( - (self._date - timedelta(days=self._date.weekday())).replace( + start_of_week.replace( hour=0, minute=0, second=0, @@ -571,8 +573,10 @@ def startOfWeek(self) -> 'Carbon': ) def endOfWeek(self) -> 'Carbon': + end_of_week = self.startOfWeek().toDatetime() + timedelta(days=6) + return Carbon( - self.startOfWeek().addDays(6).toDatetime().replace( + end_of_week.replace( hour=23, minute=59, second=59, @@ -604,7 +608,7 @@ def endOfMonth(self) -> 'Carbon': def startOfYear(self) -> 'Carbon': return Carbon( - self.startOfWeek().addDays(6).toDatetime().replace( + self._date.replace( month=1, day=1, hour=0, @@ -616,7 +620,7 @@ def startOfYear(self) -> 'Carbon': def endOfYear(self) -> 'Carbon': return Carbon( - self.startOfWeek().addDays(6).toDatetime().replace( + self._date.replace( month=12, day=31, hour=23, diff --git a/tests/test_python_carbon.py b/tests/test_python_carbon.py index 324f793..fadac7a 100644 --- a/tests/test_python_carbon.py +++ b/tests/test_python_carbon.py @@ -63,6 +63,18 @@ def test_start_and_end_methods(self) -> None: self.assertEqual(end_of_hour.second, 59) self.assertEqual(end_of_hour.microsecond, 999999) + def test_start_end_week_and_year_exact_values(self) -> None: + dt = Carbon.parse('2021-08-18 14:15:16.123456') + + self.assertEqual(dt.startOfWeek().toDateTimeString(with_milliseconds=True), '2021-08-16 00:00:00.000000') + self.assertEqual(dt.endOfWeek().toDateTimeString(with_milliseconds=True), '2021-08-22 23:59:59.999999') + self.assertEqual(dt.startOfYear().toDateTimeString(with_milliseconds=True), '2021-01-01 00:00:00.000000') + self.assertEqual(dt.endOfYear().toDateTimeString(with_milliseconds=True), '2021-12-31 23:59:59.999999') + + sunday = Carbon.parse('2021-08-22 10:00:00') + self.assertEqual(sunday.startOfWeek().toDateTimeString(), '2021-08-16 00:00:00') + self.assertEqual(sunday.endOfWeek().toDateTimeString(), '2021-08-22 23:59:59') + def test_add_sub_and_last_day_of_month(self) -> None: self.assertTrue(Carbon.parse('2021-08-31').isLastDayOfMonth())