Skip to content

Commit 2eb3837

Browse files
committed
util.parse_to_shortdate: refactor, add support for omitted year
1 parent 01013b6 commit 2eb3837

1 file changed

Lines changed: 11 additions & 9 deletions

File tree

util.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -360,22 +360,24 @@ def parse_to_shortdate(date_str, fmt=None):
360360
# pip install python-dateutil
361361
from dateutil import parser
362362

363+
current_year = datetime.now().year
364+
363365
if fmt is None: fmt = '%y%m%d'
364366
if isinstance(date_str, datetime):
365367
return date_str.strftime(fmt)
366368

367369
date_str = re.sub(r'[\s ]+', ' ', date_str).strip()
368-
patterns = [r'(\d+)年 *(\d+)月 *(\d+)日', r'(\d{4})[/\-.](\d{1,2})[/\-.](\d{1,2})']
370+
patterns = [r'(?:(?P<y>\d+)年)? *(?P<m>\d+)月 *(?P<d>\d+)日',
371+
r'(?P<y>\d{4})[/\-.](?P<m>\d{1,2})[/\-.](?P<d>\d{1,2})']
369372
for pattern in patterns:
370-
if m := re.search(pattern, date_str):
371-
date_str = m[1] + m[2].zfill(2) + m[3].zfill(2)
372-
break
373-
# Sometimes the string has extra spaces. But this is dangerous since things like `2014/3/7 23:52` will be parsed as `20140372`.
374-
# But it *should* have been caught by the `m` above already, so 99% of the cases it should be fine.
375-
if m2 := re.search(pattern, date_str.replace(' ', '')):
376-
date_str = m2[1] + m2[2].zfill(2) + m2[3].zfill(2)
373+
# Sometimes the string has extra spaces. But matching with spaces removed is dangerous
374+
# since things like `2014/3/7 23:52` will be parsed as `20140372`. But it *should* have been
375+
# caught by the first re.search already, so 99% of the cases it should be fine.
376+
if m := re.search(pattern, date_str) or re.search(pattern, date_str.replace(' ', '')):
377+
# year is assumed to be current year if not provided for kanji dates.
378+
# for numbers, it is NOT assumed because it has way too many edge cases.
379+
date_str = f"{m['y'] or current_year}-{m['m']}-{m['d']}"
377380
break
378-
379381
try:
380382
return parser.parse(date_str, yearfirst=True).strftime(fmt)
381383
except:

0 commit comments

Comments
 (0)