How to do locale date formatting in Python?

Sometimes, we want to do locale date formatting in Python.

In this article, we’ll look at how to do locale date formatting in Python.

How to do locale date formatting in Python?

To do locale date formatting in Python, we can use the locale and datetime modules

For instance, we write:

import locale
import datetime

locale.setlocale(locale.LC_TIME, '')
date_format = locale.nl_langinfo(locale.D_FMT)
d = datetime.date(2020, 4, 23)
print(d.strftime(date_format))

We call locale.setlocale to set the locale of the script.

Then we get the date format with:

date_format = locale.nl_langinfo(locale.D_FMT)

Finally, we create the date with datetime.date and format it into a date string with strftime with date_format as its argument.

Therefore, we see '04/23/2020' printed.

Conclusion

To do locale date formatting in Python, we can use the locale and datetime modules