You can also leverage the calendar module:
from calendar import month_name
months = list(month_name)
def parser (text):
"""Parses 'englishmonthname_whitespace_day-number' into string 'monthNR.dayNr'.
Will pad a zero to allow for string based sorting."""
try:
month,day = text.split()
monthAsIdx = months.index(month.strip())
return '{:02d}.{:02d}'.format(monthAsIdx,int(day)) # return index in list.days
except (ValueError, IndexError): # ValueError if not enough elements in string,
# IndexError if not in list of month names
return "99.99" # put last - all errors are put last w/o specific reordering
dates = ['TooFew', 'EnoughBut NotInList', 'March 1', 'March 9', 'April 14', 'March 12']
for n in dates:
print(parser(n))
sortedDates = sorted(dates, key=lambda x: parser(x))
print(sortedDates)
Output:
# result of parser()
99.99
99.99
03.01
03.09
04.14
03.12
# sorted by key/lambda
['March 1', 'March 9', 'March 12', 'April 14', 'TooFew', 'EnoughBut NotInList']