Fixing dates


In the input we get dates like this 2010-7-5 but we would like to make sure we have two digits for both days and months: 2010-07-05


examples/regex/date.py
import re

def fix_date(date):
    return re.sub(r'-(\d)\b', r'-0\1', date)


dates = {
    '2010-7-5'   : '2010-07-05',
    '2010-07-5'  : '2010-07-05',
    '2010-07-05' : '2010-07-05',
    '2010-7-15'  : '2010-07-15',
}

for original in sorted(dates.keys()):
    result = fix_date(original)

    assert result == dates[original]

    print(f"      old: {original}")
    print(f"      new: {result}")
    print(f" expected: {dates[original]}")
    print("")

      old: 2010-07-05
      new: 2010-07-05
 expected: 2010-07-05

      old: 2010-07-5
      new: 2010-07-05
 expected: 2010-07-05

      old: 2010-7-15
      new: 2010-07-15
 expected: 2010-07-15

      old: 2010-7-5
      new: 2010-07-05
 expected: 2010-07-05