[Answered ]-Regex: how to extract incomplete date and convert

1👍

You should build patterns for each year, month and day and match them all in one expression (making month and day optional):

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')
👤Tranbi

Leave a comment