最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]Python中datetime的strftime中format中是unicode结果出错:UnicodeEncodeError ascii codec can’t encode character in position ordinal not in range

Python crifan 3566浏览 0评论

Python的代码:

@app.template_filter(‘date_format’)
def _jinja2_filter_datetime_format(datetimeValue, format=u’%m月%d日’):
    “””convert a date to a different format.”””
    gLog.debug(“type(datetimeValue)=%s, datetimeValue=%s, format=%s”, type(datetimeValue), datetimeValue, format)
    # type(dateValue)=<type ‘builtin_function_or_method’>, dateValue=<built-in method date of datetime.datetime object at 0x7efccf27ea30>, format=%m月%d日
    formattedDate = datetimeValue.strftime(format)
    gLog.debug(“type(formattedDate)=%s, formattedDate=%s”, type(formattedDate), formattedDate)
    return formattedDate

结果出错:

type(datetimeValue)=<type ‘datetime.datetime’>, datetimeValue=2016-09-02 20:45:00, format=%m月%d日

<div–<——————————————————————————

[2016-09-06 14:44:59 +0000] [15282] [ERROR] Error handling request /
Traceback (most recent call last):
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/sync.py”, line 135, in handle
    self.handle_request(listener, req, client, addr)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/sync.py”, line 176, in handle_request
    respiter = self.wsgi(environ, resp.start_response)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py”, line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py”, line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py”, line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py”, line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py”, line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py”, line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py”, line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py”, line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File “/root/html/SIPEvents/sipevents/views.py”, line 829, in decorated_function
    return f(*args, **kwargs)
  File “/root/html/SIPEvents/sipevents/views.py”, line 906, in index
    futureEventList = futureEventList)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/templating.py”, line 134, in render_template
    context, ctx.app)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/templating.py”, line 116, in _render
    rv = template.render(context)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/jinja2/environment.py”, line 989, in render
    return self.environment.handle_exception(exc_info, True)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/jinja2/environment.py”, line 754, in handle_exception
    reraise(exc_type, exc_value, tb)
  File “/root/html/SIPEvents/sipevents/templates/index.html”, line 117, in top-level template code
    <span>{{ expiredEvent.start_date | date_format }}</span>
  File “/root/html/SIPEvents/sipevents/views.py”, line 434, in _jinja2_filter_datetime_format
    formattedDate = datetimeValue.strftime(format)
UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\u6708′ in position 2: ordinal not in range(128)

python strftime UnicodeEncodeError

Using a Unicode format for Python’s `time.strftime()` – Stack Overflow

datetime – UnicodeEncodeError when parsing month name with Python strptime – Stack Overflow

最后改为:

@app.template_filter(‘date_format’)
# def _jinja2_filter_datetime_format(datetimeValue, format=u’%m月%d日’):
def _jinja2_filter_datetime_format(datetimeValue, format=’%m月%d日’):
    “””convert a date to a different format.”””
    gLog.debug(“type(datetimeValue)=%s, datetimeValue=%s, format.decode(‘utf-8’)=%s”, type(datetimeValue), datetimeValue, format.decode(“utf-8”))
    # type(dateValue)=<type ‘builtin_function_or_method’>, dateValue=<built-in method date of datetime.datetime object at 0x7efccf27ea30>, format=%m月%d日
    # formatUtf8 = format.encode(“UTF-8”)
    # gLog.debug(“formatUtf8=%s”, formatUtf8)
    # formattedDate = datetime.strftime(datetimeValue, formatUtf8)
    formattedDate = datetime.strftime(datetimeValue, format)
    formattedDateUnicode = formattedDate.decode(‘utf-8’)
    gLog.debug(“type(formattedDate)=%s, formattedDateUnicode=%s”, type(formattedDate), formattedDateUnicode)
    return formattedDateUnicode

即可:

DEBUG in views [/root/html/SIPEvents/sipevents/views.py:433]:
type(datetimeValue)=<type ‘datetime.datetime’>, datetimeValue=2016-09-02 22:23:00, format.decode(‘utf-8’)=%m月%d日

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in views [/root/html/SIPEvents/sipevents/views.py:440]:
type(formattedDate)=<type ‘str’>, formattedDateUnicode=09月02日

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in views [/root/html/SIPEvents/sipevents/views.py:446]:
type(datetimeValue)=<type ‘datetime.datetime’>, datetimeValue=2016-09-02 22:23:00, format=%p %H:%M

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in views [/root/html/SIPEvents/sipevents/views.py:448]:
formattedTime=PM 22:23

转载请注明:在路上 » [已解决]Python中datetime的strftime中format中是unicode结果出错:UnicodeEncodeError ascii codec can’t encode character in position ordinal not in range

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.164 seconds, using 22.00MB memory