I want to create a "unicode sandwich" that includes some date/time values and is locale independent. For the uninitiated, the term unicode sandwich describes the practice of converting from bytes to unicode and back at the boundaries of your program, i.e. bytes on the outside and unicode on the inside.
I watched Ned Batchelder's excellent video on unicode this morning and am attempting to convert some of my code to be consistent with his wise advice.
The problem I'm having is I can't work out how to determine the encoding of a string returned by str(date)
or its equivalents. What I have in mind is to do something like this, a little verbose for clarity:
date_str_encoding = some_magical_method_I_have_yet_to_discover()
date = datetime.datetime(2013, 10, 16).date()
date_str = date.strftime('%A %B %d, &Y') # perhaps 'Sábado Octubre 19, 2013'
date_unicode = date_str.decode(date_str_encoding)
One of Ned's unicode "facts of life" is "You cannot infer the encoding of bytes. You must be told or you have to guess." Unfortunately, I can't find that particular detail in the Python docs for datetime.
Another SO post mentioned the use of locale.getlocale(), but that returns (None, None) for me.
How can I reliably discover the encoding of a Python date string at run time?
ASCII
. What's your question exactly? – Paulo Bu Oct 16 '13 at 20:18None
returned for that value.locale.getdefaultlocale()
returns a plausible value, but won't be correct necessarily if someone has set the locale to something else. Could it be I have to check getlocale() and fall back to getdefaultlocale() if the former returns None? I can't believe the Python library guys would have done it that way, did they? – scanny Oct 16 '13 at 20:47