How to get the correct date format string for a given locale without installing this locale in Python?

I am trying to create dictionaries containing dates that can be set in specific locales. For example, I might need to return my function when called with en_US as an argument:

{'date': 'May 12, 2014', ...} 

And this is when called with hu_HU:

 {'date': '2014. mรกjus 12.', ...} 

Now, based on what I have found so far, I have to use locale.setlocale() to set the locale I want to use, and locale.nl_langinfo(locale.D_FMT) to get the appropriate date format. I could call locale.resetlocale() after that to return to the previously used one, but my program uses several threads, and I believe that others will be affected by this temporary change of locale.

+6
source share
2 answers

There is a non-standard babel module that offers this and much more:

 >>> import babel.dates >>> babel.dates.format_datetime(locale='ru_RU') '12  2014 ., 8:24:08' >>> babel.dates.format_datetime(locale='de_DE') '12.05.2014 08:24:14' >>> babel.dates.format_datetime(locale='en_GB') '12 May 2014 08:24:16' >>> from datetime import datetime, timedelta >>> babel.dates.format_datetime(datetime(2014, 4, 1), locale='en_GB') '1 Apr 2014 00:00:00' >>> babel.dates.format_timedelta(datetime.now() - datetime(2014, 4, 1), locale='en_GB') '1 month' 
+5
source

It can be expensive, but how about you build a country code: datetime format records dictionary before starting your threads?

 for lang in lang_codes: locale.setlocale(lang) time_format[lang] = locale.nl_langinfo(locale.D_FMT) locale.resetlocale() 

Then you can use format strings when you need a date in a specific format time.strftime(time_format[lang], t) . Of course, this will not take care of changing GMT.

The best way would be to find where the locale gets its mapping, but I don't know this and don't have time to research right now.

+1
source

All Articles