Skip to content

Commit 28c4629

Browse files
MarcoGorelliabkosar
authored andcommitted
BUG: guess_datetime_format doesn't guess just year (#49127)
* guess %Y format * fixup Co-authored-by: MarcoGorelli <>
1 parent 9049179 commit 28c4629

File tree

2 files changed

+7
-3
lines changed

2 files changed

+7
-3
lines changed

pandas/_libs/tslibs/parsing.pyx

+6-2
Original file line numberDiff line numberDiff line change
@@ -1053,8 +1053,12 @@ def guess_datetime_format(dt_str: str, bint dayfirst=False) -> str | None:
10531053
found_attrs.update(attrs)
10541054
break
10551055

1056-
# Only consider it a valid guess if we have a year, month and day
1057-
if len({'year', 'month', 'day'} & found_attrs) != 3:
1056+
# Only consider it a valid guess if we have a year, month and day,
1057+
# unless it's %Y which is both common and unambiguous.
1058+
if (
1059+
len({'year', 'month', 'day'} & found_attrs) != 3
1060+
and format_guess != ['%Y']
1061+
):
10581062
return None
10591063

10601064
output_format = []

pandas/tests/tslibs/test_parsing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ def test_parsers_month_freq(date_str, expected):
147147
[
148148
("20111230", "%Y%m%d"),
149149
("2011-12-30", "%Y-%m-%d"),
150+
("2011", "%Y"),
150151
("30-12-2011", "%d-%m-%Y"),
151152
("2011-12-30 00:00:00", "%Y-%m-%d %H:%M:%S"),
152153
("2011-12-30T00:00:00", "%Y-%m-%dT%H:%M:%S"),
@@ -208,7 +209,6 @@ def test_guess_datetime_format_with_locale_specific_formats(string, fmt):
208209
@pytest.mark.parametrize(
209210
"invalid_dt",
210211
[
211-
"2013",
212212
"01/2013",
213213
"12:00:00",
214214
"1/1/1/1",

0 commit comments

Comments
 (0)