python3 datetime.datetime.strftime failed to accept utf-8 string format

python3 datetime.datetime.strftime failed to accept utf-8 string format

what I did is::

# encoding: utf-8
import datetime

f = "%Y年%m月%d日"
now = datetime.datetime.now()
print( now.strftime(f) )

and what I get is:

D:\pytools>python a.py
Traceback (most recent call last):
  File "a.py", line 6, in <module>
    print( now.strftime(f) )
UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2
: Illegal byte sequence

Why and how can I fix this?

Answers


The problem is not in datetime, it's in print. See PrintFails

Ah, it's not exactly that - although it has the same cause, and you're likely to have that problem writing Unicode to stdout. (Using an IDE with a Python shell eg an up-to-date IDLE, avoids this.)

The strftime() function which is what datetime.strftime() ends up calling, is part of the C standard library, which under Windows/MSVCRT can't deal with Unicode strings. (Although in theory you could work around it by setting code page to 65001 and using UTF-8, there are serious long-standing bugs in the C runtime for that code page.)

Workaround in Python could be to replace out the non-ASCII characters until after the call:

strftime('%Y{0}%m{1}%d{2}').format(*'年月日')

Or to eschew strftime and do it yourself.

This should probably be considered a bug in time.strftime() and fixed there, by either of these means. It would make sense to add a Python-native implementation of strftime - they have already had to do the same for strptime due to other platform bugs in that function.


Need Your Help

Deploy Java EE application as root context on WildFly

eclipse java-ee jboss wildfly

I'm using Eclipse Mars IDE + JBoss AS (WildFly 9.0.1). Then I launch the server and all is OK. I would like to know how to set an applicatioin as root context?.

C#, Binary Serialization over Socket Communication

c# sockets visual-studio-2008 network-programming

I use Binary Serialization Object to Read or Write Data Stream and previously if we are going to write/read them we have to compile the "instance class" to be DLL file so we have same Assemblies be...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.