正则表达式:如何提取不完整的日期并进行转换

Regex: how to extract incomplete date and convert

如何获取不包含月份或日期的日期?

现在我只知道日期怎么打

date_n= '2022-12'
match_year = re.search(r'(?P<year_only>(?P<year>\d+))', date_n)
match_month = re.search(r'(?P<whole_date>(?P<year>\d+)-(?P<month>\d+))', date_n)
match_day = re.search(r'(?P<whole_date>(?P<year>\d+)-(?P<month>\d+)-(?P<day>\d+))', date_n)

year = match_year.group('year_only')
month = match_month.group('month')
day = match_day.group('day')

Try and Except 不起作用。

您应该为每个 yearmonthday 构建模式并在一个表达式中匹配它们(使 monthday 可选) :

import re

date_n= '2022-12'
year_pattern = r"(?P<year>\d{4})"
month_pattern = r"(?:-(?P<month>\d{1,2}))"
day_pattern = r"(?:-(?P<day>\d{1,2}))"
match_date = re.search(rf'{year_pattern}(?:{month_pattern}{day_pattern}?)?', date_n)

year = match_date.group('year')
month = match_date.group('month')
day = match_date.group('day')