Robbert Bos

October 5, 2022

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

python-locale.png


Did you know you can easily switch to local formats using Python 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

About Robbert Bos

I love to make data analytics, data science, AI and ML projects easier to run, more transparent to use and fun to collaborate on. With AskAnna, I work on a platform that supports this. On HEY World I write about it.