Force locale for one function to be UK/English in just one function so that datetime.strftime always returns an English format
I need to write a very simple python function which accepts a date in Excel format (an integer of days elapsed since 1st Jan 1900). I convert that to a python datetime.date object, and finally I'd like to format that as a shortened string date (e.g. "Jan10" or "Mar11") - basically the date in MmmYY format.
dt.strftime( fmt )
This function works just fine on UK & US workstations, however I've noticed that on some colleagues PCs which are set to a French locale we get the wrong anser:
>>> locale.getdefaultlocale()
('fr_FR', 'cp1252')
On these machines the function above returns the formatted date-string in French which is not the desired output.
I understand that I could use the locale.setlocale function to globally re-define the locale, however this is not something which is desirable. Elsew开发者_开发百科here in the system there is likely to be scripts which require a native-language locale. I do not wish to break somebody else's component by re-defining a global locale.
So what can I do? Short of re-writing the string-formatting function, is there a way I can make the strftime function produce it's output in the UK/US locale without affecting anything else?
Platform = Python2.4.4 on Windows 32bit
FYI, this solution does not apply - it changes the locale globally which is exactly what I want to avoid doing: Locale date formatting in Python
If you need fixed strings then it's probably best to create a mapping of month number to month name and just use that.
months = {1: 'Jan', 2: 'Feb', ...}
printf '%s%02d' % (months[somedt.month], somedt.year % 100)
Yes, this is possible to do. I've had this same problem when implementing a web server. I wanted the date/time to appear in the client web browser's locale, not the server's local.
In the standard library, there is a locale module. Check out the setlocale() and getlocale() methods, specifically wit the category LC_TIME. You'll probably want to use getlocale() to get the existing locale, then setlocale to set it to something like 'EN_US' or 'C", then call the strftime method, and finally restore the previous local with another setlocale() call.
精彩评论