Blob
Blob

Reputation: 381

Converting month string to number in date

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"

Upvotes: 0

Views: 66

Answers (2)

couteau
couteau

Reputation: 319

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

Upvotes: 0

Adon Bilivit
Adon Bilivit

Reputation: 27008

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

Upvotes: 1

Related Questions