Skip to content

Commit b67668e

Browse files
fix: incorrect ISO week 53 conversion when only 52 weeks exist (#60896)
* fix: incorrect ISO week 53 conversion when only 52 weeks exist * test(invalid_iso_week): ready, set, go! * test: removing unwanted errors="raise" as those are the defaults.
1 parent e3f544d commit b67668e

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

pandas/_libs/tslibs/strptime.pyx

+7
Original file line numberDiff line numberDiff line change
@@ -924,6 +924,13 @@ cdef (int, int) _calc_julian_from_V(int iso_year, int iso_week, int iso_weekday)
924924

925925
correction = date(iso_year, 1, 4).isoweekday() + 3
926926
ordinal = (iso_week * 7) + iso_weekday - correction
927+
928+
if iso_week == 53:
929+
now = date.fromordinal(date(iso_year, 1, 1).toordinal() + ordinal - iso_weekday)
930+
jan_4th = date(iso_year+1, 1, 4)
931+
if (jan_4th - now).days < 7:
932+
raise ValueError(f"Week 53 does not exist in ISO year {iso_year}.")
933+
927934
# ordinal may be negative or 0 now, which means the date is in the previous
928935
# calendar year
929936
if ordinal < 1:

pandas/tests/tools/test_to_datetime.py

+24
Original file line numberDiff line numberDiff line change
@@ -794,12 +794,36 @@ def test_to_datetime_np_str(self):
794794
["2015-1-1", "%G-%V-%u", datetime(2014, 12, 29, 0, 0)],
795795
["2015-1-4", "%G-%V-%u", datetime(2015, 1, 1, 0, 0)],
796796
["2015-1-7", "%G-%V-%u", datetime(2015, 1, 4, 0, 0)],
797+
["2024-52-1", "%G-%V-%u", datetime(2024, 12, 23, 0, 0)],
798+
["2024-52-7", "%G-%V-%u", datetime(2024, 12, 29, 0, 0)],
799+
["2025-1-1", "%G-%V-%u", datetime(2024, 12, 30, 0, 0)],
800+
["2020-53-1", "%G-%V-%u", datetime(2020, 12, 28, 0, 0)],
797801
],
798802
)
799803
def test_to_datetime_iso_week_year_format(self, s, _format, dt):
800804
# See GH#16607
801805
assert to_datetime(s, format=_format) == dt
802806

807+
@pytest.mark.parametrize(
808+
"msg, s, _format",
809+
[
810+
[
811+
"Week 53 does not exist in ISO year 2024",
812+
"2024 53 1",
813+
"%G %V %u",
814+
],
815+
[
816+
"Week 53 does not exist in ISO year 2023",
817+
"2023 53 1",
818+
"%G %V %u",
819+
],
820+
],
821+
)
822+
def test_invalid_iso_week_53(self, msg, s, _format):
823+
# See GH#60885
824+
with pytest.raises(ValueError, match=msg):
825+
to_datetime(s, format=_format)
826+
803827
@pytest.mark.parametrize(
804828
"msg, s, _format",
805829
[

0 commit comments

Comments
 (0)