About

Unicode troubleshooting : strftime in Jinja2

Say, in Python2, if we need to format a datetime object with some unicode in the format, what shall we do?

The following code looks perfect

Code Snippet 0-0

# encoding=utf-8

import jinja2
import datetime

now = datetime.datetime.now()

print(jinja2.Template(u'''{{ date.strftime('%Y 年 %m 月') }}''').render(date=now))

Except that it raises a UnicodeEncodeError.

Code Snippet 0-1

Traceback (most recent call last):
 File "test.py", line 8, in

   print(jinja2.Template(u'''{{ date.strftime('%Y 年 %m 月') }}''').render(date=now))
 File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 1008, in render
   return self.environment.handle_exception(exc_info, True)
 File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 780, in handle_exception
   reraise(exc_type, exc_value, tb)
 File "

Tags: Python

Loading comments


. Back to Tobary book
Tobary book - Copyright (C) ZhePlus @ Bit Focus
About