-1

I need to get translated month names to provided language. Is there any correct way or good practice to get localized month names in python 3.X? Language i will get from request

def get_localized_month(num: int, lang: str = "ru") -> str:
    months = {
        1: {
            "en": "January",
            "ru": "Январь",
            "others": "Январь",
        },
        2: {
            "en": "February",
            "ru": "Февраль",
            "others": "Февраль",
        },
    }
    return months[num][lan]

2 Answers2

0
import calendar

def get_localized_month(num: int, lang: str = "ru") -> str:
    # Convert the month number to 1-based indexing used by the calendar module
    month_idx = num - 1
    # Get the list of month names for the given language
    month_names = getattr(calendar, f'month_name_{lang.lower()}')
    # Get the localized month name from the list
    return month_names[month_idx]
-1

Perhaps this is a job for a Python Package.

Looking on PyPI, the first package I found was translate.

Using this package you could update your code to the following:

from translate import Translator

def get_localized_month(num: int, lang: str = "ru") -> str:
    translator = Translator(to_lang=lang)
    months = {
        1: 'January',
        2: 'February',
        3: 'March',
        4: 'April',
        5: 'May',
        6: 'June',
        7: 'July',
        8: 'August',
        9: 'September',
        10: 'October',
        11: 'November',
        12: 'December'
    }
    return translator.translate(months[num])

Whether this is the right choice may require some more research. Play around with the package in your console for a little, test to see if it works the way you want it too. If it doesn't, there are other packages you could look to.

eliaseraphim
  • 101
  • 4