Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Unicode format for Python's `time.strftime()`

Tags:

python

unicode

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?

like image 856
Hosam Aly Avatar asked Apr 03 '10 14:04

Hosam Aly


People also ask

What is time Strftime in Python?

time. strftime (format[, t]) Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument. If t is not provided, the current time as returned by localtime() is used. format must be a string.

How do you change time format 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.

What does Strftime stand for?

strftime means string from time . we can format the time in different desirable ways. This is the name reason only.


2 Answers

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

import time
my_format = u'%d\u200f/%m\u200f/%Y %H:%M:%S'
my_time   = time.localtime()
time.strftime(my_format.encode('utf-8'), my_time).decode('utf-8')
like image 120
AndiDog Avatar answered Oct 05 '22 16:10

AndiDog


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')
like image 27
Yaroslav Avatar answered Oct 05 '22 18:10

Yaroslav