strftime return value encoding (mbcs, locale, etc.)

Giovanni Bajo rasky at develer.com
Sun Jan 27 21:15:55 CET 2008


Hello,

I am trying to find a good way to portably get the output of strftime() 
and put it onto a dialog (I'm using PyQt, but it doesn't really matter). 
The problem is that I need to decode the byte stream returned by strftime
() into Unicode.

This old bug:
http://mail.python.org/pipermail/python-bugs-list/2003-
November/020983.html

(last comment) mentions that it is "byte string in the locale's encoding".

The comment also suggests to use "mbcs" in Windows (which, AFAIK, it's 
sort of an "alias" encoding for the current Windows codepage), and to 
find out the exact encoding using locale.getpreferredencoding().

Thus, I was hoping that something like:

  strftime("%#c", localtime()).decode(locale.getpreferredencoding())

would work... but alas I was reported this exception:

  LookupError: unknown encoding: cp932

So: what is the correct code to achieve this? Will something like this 
work:

  data = strftime("%#c", localtime())
  if os.name == "nt":
     data = data.decode("mbcs")
  else:
     data = dada.decode(locale.getpreferredencoding())

Is this the correct way of doing it? (Yes, it sucks).

Shouldn't Python automatically alias whatever is returned by 
locale.getpreferredencoding() to "mbcs", so that my original code works 
portably?

Thanks in advance!
-- 
Giovanni Bajo



More information about the Python-list mailing list