Search code examples
pythonpython-2.7locale

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


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.


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'