Make sure locale is installed if you use locale in your Python code

author.name Robbert, 5 October 2022

Did you know you can easily switch to local formats using Python’s locale? For example, you can use this code snippet to print the date in the local language:

import locale
from datetime import datetime

date = datetime.now()

locale.setlocale(locale.LC_TIME, "nl_NL.UTF-8")
print(date.strftime("%d %B %Y").lstrip("0"))

What I didn’t know was that by default not on all systems the locale is installed. I discovered this the hard way while developing with a Docker container based on Alpine. While the above code snippet worked, it printed the output in the default language. It took me some time to figure out that the locale is not installed on Alpine by default.

After knowing the cause, it was pretty easy to fix it. In the Dockerfile I added the following lines:

ENV MUSL_LOCPATH="/usr/share/i18n/locales/musl"
RUN apk add --no-cache --update musl-locales