Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 770
Underyx Avatar asked May 12 '14 07:05

Underyx


People also ask

How do I format a date string in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

How does Python determine date format?

The function to get a datetime from a string, datetime. strptime(date_string, format) requires a string format as the second argument.


1 Answers

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'
like image 168
Jonas Schäfer Avatar answered Sep 20 '22 05:09

Jonas Schäfer