Skip to content

Commit 5a7aaa1

Browse files
authored
Merge pull request #1510 from lee3Q/fix-1435-yearless-parsing
Avoid yearless date parsing warnings while preserving parse errors
2 parents 4745b35 + ebb2693 commit 5a7aaa1

4 files changed

Lines changed: 96 additions & 2 deletions

File tree

‎AUTHORS.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,4 @@ Rajvira10
6767
Ben Finney - ben+python [at] benfinney [dot] id [dot] au
6868
Stefano Debenedetti - 44903077+demaledetti [at] users [dot] noreply [dot] github [dot] com
6969
TheeCoderAhmed
70+
lee3Q

‎CHANGELOG.rst‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ unreleased
3131
date only; such an EXDATE now excludes all instances on that day
3232
* FIX an invalid alarm in ``khal edit`` or ``khal new -i`` crashed with a
3333
traceback, it is now reported and the menu is shown again
34+
* FIX parsing dates without a year (e.g. ``khal new 17.03.``) no longer
35+
triggers a ``DeprecationWarning`` on Python 3.13+ and works with Python
36+
3.15, where such parsing raises an error
3437

3538
0.14.1
3639
======

‎khal/parse_datetime.py‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,25 @@ def timefstr(dtime_list: list[str], timeformat: str) -> dt.datetime:
5555
return dtstart
5656

5757

58+
# directives that set the year themselves (%y %Y %G %c %x) or whose meaning
59+
# depends on it (%j %U %W)
60+
_YEAR_DIRECTIVES = re.compile(r"%[yYGgjUWcx]")
61+
62+
63+
def _can_add_year(dateformat: str, dtstring: str) -> bool:
64+
"""whether a year can be appended to `dateformat` and `dtstring` to parse
65+
them with strptime() without changing the result
66+
67+
Formats or input with surrounding whitespace keep the old parsing path,
68+
so they fail the same way as before.
69+
"""
70+
return (
71+
dateformat == dateformat.strip()
72+
and dtstring == dtstring.strip()
73+
and not _YEAR_DIRECTIVES.search(dateformat.replace("%%", ""))
74+
)
75+
76+
5877
def datetimefstr(
5978
dtime_list: list[str],
6079
dateformat: str,
@@ -79,8 +98,13 @@ def datetimefstr(
7998
default_day = now.date()
8099
parts = dateformat.count(" ") + 1
81100
dtstring = " ".join(dtime_list[0:parts])
82-
# only time.strptime can parse the 29th of Feb. if no year is given
83-
dtstart_struct = strptime(dtstring, dateformat)
101+
# strptime() without a year is deprecated (an error since Python 3.15) and
102+
# cannot parse the 29th of Feb., so parse with a leap year; the actual
103+
# year is inferred below
104+
if infer_year and _can_add_year(dateformat, dtstring):
105+
dtstart_struct = strptime(f"{dtstring} 2000", f"{dateformat} %Y")
106+
else:
107+
dtstart_struct = strptime(dtstring, dateformat)
84108
if (
85109
infer_year
86110
and dtstart_struct.tm_mon == 2

‎tests/parse_datetime_test.py‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import datetime as dt
2+
import warnings
23
from collections import OrderedDict
34

45
import pytest
@@ -8,6 +9,7 @@
89
from khal.icalendar import new_vevent
910
from khal.parse_datetime import (
1011
construct_daynames,
12+
datetimefstr,
1113
eventinfofstr,
1214
guessdatetimefstr,
1315
guessrangefstr,
@@ -546,6 +548,70 @@ def test_leap_year():
546548
assert _replace_uid(event).to_ical() == vevent
547549

548550

551+
def test_datetimefstr_without_year_does_not_warn():
552+
with warnings.catch_warnings():
553+
warnings.simplefilter("error")
554+
parsed = datetimefstr(["17.03.", "16:00"], "%d.%m. %H:%M", dt.date(2016, 9, 19))
555+
assert parsed == dt.datetime(2017, 3, 17, 16, 0)
556+
leap = datetimefstr(["29.02."], "%d.%m.", dt.date(2016, 1, 1), in_future=False)
557+
assert leap == dt.datetime(2016, 2, 29)
558+
with pytest.raises(ValueError, match="^$"):
559+
datetimefstr(["29.02."], "%d.%m.", dt.date(2015, 1, 1))
560+
561+
562+
@pytest.mark.parametrize(
563+
("dateformat", "text"),
564+
[
565+
("%d.%m.%%Y", "17.03.%Y"),
566+
("%%j %d.%m.", "%j 17.03."),
567+
("%%%d.%m.", "%17.03."),
568+
],
569+
)
570+
def test_datetimefstr_escaped_percent_is_not_a_year_directive(dateformat, text):
571+
with warnings.catch_warnings():
572+
warnings.simplefilter("error")
573+
result = datetimefstr(text.split(" "), dateformat, dt.date(2016, 9, 19))
574+
assert result == dt.datetime(2017, 3, 17)
575+
576+
577+
@pytest.mark.parametrize(
578+
("dateformat", "text", "expected"),
579+
[
580+
("%d.%m.%Y", "17.03.2016", dt.datetime(2016, 3, 17)),
581+
("%d.%m.%y", "17.03.16", dt.datetime(2016, 3, 17)),
582+
("%j", "076", dt.datetime(1900, 3, 17)),
583+
],
584+
)
585+
def test_datetimefstr_year_directives_still_parsed(dateformat, text, expected):
586+
with warnings.catch_warnings():
587+
warnings.simplefilter("error")
588+
result = datetimefstr([text], dateformat, dt.date(2016, 9, 19), infer_year=False)
589+
assert result == expected
590+
591+
592+
@pytest.mark.parametrize(
593+
("dtime_list", "dateformat"),
594+
[
595+
(["17.03."], "%d.%m. "),
596+
(["17.03. "], "%d.%m."),
597+
([" 17.03."], "%d.%m."),
598+
],
599+
)
600+
@pytest.mark.filterwarnings("ignore::DeprecationWarning")
601+
def test_datetimefstr_surrounding_whitespace_still_rejected(dtime_list, dateformat):
602+
with pytest.raises(ValueError, match="does not match|unconverted|without a year"):
603+
datetimefstr(dtime_list, dateformat, dt.date(2016, 9, 19))
604+
605+
606+
@pytest.mark.filterwarnings("ignore::DeprecationWarning")
607+
def test_guessdatetimefstr_dateformat_with_trailing_space_raises_parse_error():
608+
locale = dict(LOCALE_BERLIN)
609+
locale["dateformat"] = "%d.%m. "
610+
locale["datetimeformat"] = "%d.%m. %H:%M"
611+
with pytest.raises(DateTimeParseError):
612+
guessdatetimefstr(["17.03."], locale, default_day=dt.date(2024, 1, 1))
613+
614+
549615
test_set_description = _create_testcases(
550616
# now events where the start date has to be inferred, too
551617
# today

0 commit comments

Comments
 (0)