Coding problem Solving in Python

Source: Internet
Author: User
Tags datetime in python

In the py2.7 project with the __future__ module in the Unicode_literals to prepare for compatible py3.x, today encountered a unicodeencodeerror error, followed, found that this small pit is worth noting. What kind of a pit is it? Follow the code to see. By the way, the principle.
1. Unicode_literals Version not introduced

The code is as follows Copy Code

#coding: Utf-8
From datetime import datetime

now = DateTime.Now ()
Print Now.strftime ('%m month%d days%h:%m ')

This code can perform the output correctly: March 12 21:53
2. Introduction of Unicode_literals

The code is as follows Copy Code

#coding: Utf-8
From __future__ import unicode_literals
From datetime import datetime

now = DateTime.Now ()
Print Now.strftime ('%m month%d days%h:%m ')

The following error was thrown:

Traceback (most recent call last):
File "unicode_error_demo2.py", line 7, in <module>
Print Now.strftime ('%m month%d days%h:%m ')
Unicodeencodeerror: ' ASCII ' codec can ' t encode character U ' u6708 ' in position-not in range (128)

3. Solution One: Set Run-time encoding to Utf-8

The code is as follows Copy Code

#coding: Utf-8
From __future__ import unicode_literals
Import Sys
From datetime import datetime

Reload (SYS)
Sys.setdefaultencoding (' Utf-8 ')

now = DateTime.Now ()
Print Now.strftime ('%m month%d days%h:%m ')

Normal execution

4. Solution Two: Use byte string

  code is as follows copy code

#coding: Utf-8
from __future__ import unicode_literals
to datetime import datetime

now = DateTime.Now ()
Print Now.strftime (b '%m month%d%h:%m ')   # is indicated as the ByteArray string

# or it is also OK
T = ByteArray ('%m month%d%h:%m ', ' utf-8 ')
Print Now.strftime (str (t))

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.