0

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"

Blob
  • 371
  • 1
  • 9

2 Answers2

1

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

DarkKnight
  • 19,739
  • 3
  • 6
  • 22
  • Thanks for your suggestion. I just thought using re library would make this function more robust, as I am not sure if dates may occur in the format 01.Juli.22 for example – Blob Oct 10 '22 at 16:52
  • 1
    @Blob - This approach will still work if you can write a regular expression with capture groups that will match any format you are likely to encounter. E.g., `m = re.match(r'(\d{1,2})[./-]([A-Z][a-z]*)[./-]?(\d\d(?:\d\d))', data)` will match 1.Januar22 or 01.Januar2022 or 01.Januar.2022 or 01-Januar-2022, etc. and allow you to access the individual components using the resulting `Match` object. – couteau Oct 10 '22 at 17:03
  • @Blob You need to know what the potential formats are. As clever as it is, *re* isn't clairvoyant – DarkKnight Oct 10 '22 at 17:22
0

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
couteau
  • 101
  • 1
  • 5