How do I get the correct date format string for a given locale without setting that locale program-wide in Python?

StackOverflow https://stackoverflow.com/questions/23603709

  •  20-07-2023
  •  | 
  •  

Question

I'm trying to generate dictionaries that include dates which can be asked to be given in specific locales. For example, I might want my function to return this when called with en_US as an argument:

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

And this, when called with hu_HU:

{'date': '2014. május 12.', ...}

Now, based on what I've found so far, I should be using 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 this to go back to the previously used one, but my program uses multiple threads, and I assume the other ones will be affected by this temporary locale change as well.

Was it helpful?

Solution

There is the non-standard babel module which offers this and a lot 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'

OTHER TIPS

It might be expensive to do but how about before starting your threads you build a dictionary of country code: datetime format entries?

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

You can then use the format strings whenever you need the date in a specific format time.strftime(time_format[lang], t). Of course, this doesn't take care of GMT shifts.

The better way would be to find where locale gets its mapping from but I don't know that and don't have the time to investigate right now.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top