Converting month string to number in date

Question:

Is there a better way to convert the month string to a number? The month names are provided in language different to the locale so I can’t use the %B in datetime. Adjusting the local is not an option.

def stringMonthToNumber(data):
    data= re.sub("Januar", "01.", data)
    ...
    data= re.sub("Dezember", "12.", data)
    return data

data = "01.Januar2022"

Asked By: Blob

||

Answers:

If the format of the source string is exactly as shown in the question then this will suffice:

MONTHS = {
    'Januar': '01',
    'Februar': '02',
    'März': '03',
    'Maerz': '03',
    'April': '04',
    'Mai': '05',
    'Juni': '06',
    'Juli': '07',
    'August': '08',
    'September': '09',
    'Oktober': '10',
    'November': '11',
    'Dezember': '12'
}

def convert(ds):
    return ds[:3] + MONTHS[ds[3:-4]] + '.' + ds[-4:]

print(convert('01.Juli2022'))

Output:

01.07.2022

It is assumed that the input string leads with DD. and ends with YYYY.

It is also assumed that the language is German

Answered By: OldBill

Assuming your input will always be in the format in your example, how about:

months = {
    'Januar': '01.',
    ...
    'Dezember': '12.'
}

def stringMonthToNumber(data):
    month = data[3:-4]
    if month not in months:
        raise ValueError(f'Invalid month in date: {data}')

    data= f'{data[0:3]}{months[month]}{data[-4:]}'
    return data
Answered By: couteau
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.