tags:

views:

85

answers:

2

I am trying to call Python's time.strftime() function using a Unicode format string:

u'%d\u200f/%m\u200f/%Y %H:%M:%S'

(\u200f is the "Right-To-Left Mark" (RLM).)

However, I am getting an exception that the RLM character cannot be encoded into ascii:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u200f' in position 2: ordinal not in range(128)

I have tried searching for an alternative but could not find a reasonable one. Is there an alternative to this function, or a way to make it work with Unicode characters?

+3  A: 

You can format string through utf-8 encoding:

time.strftime(u'%d\u200f/%m\u200f/%Y %H:%M:%S'.encode('utf-8'), t).decode('utf-8')
Yaroslav
Thank you. This is the same as @AndiDog's answer, but since he answered first I'll choose his to be the accepted answer.
Hosam Aly
@Alex, thanks. I've fixed it.
Yaroslav
+2  A: 

Many standard library functions still don't support Unicode the way they should. You can use this workaround:

time.strftime(u'%d\u200f/%m\u200f/%Y %H:%M:%S'.encode('utf-8'), <your time here>).decode('utf-8')
AndiDog
Thank you. This works nicely.
Hosam Aly
Mind that Python 3 will behave differently, see my bug report (http://bugs.python.org/issue8304).
AndiDog