UnicodeDecodeError:' utf8'编解码器不能解码位置18中的字节0xe9:无效的连续字节

时间:2017-10-11 22:37:53

标签: python

我试图将日期时间列输出到json.But我在Python 2.7中收到此错误:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 18: invalid continuation byte

这是一个示例数据:

>>> data
            id impact_date             store     country  \
0      6244543  2017-10-10  ARGENTINA   ARGENTINA
1      6244544  2017-10-10  ARGENTINA   ARGENTINA
2      6244545  2017-10-10  ARGENTINA   ARGENTINA
3      6244546  2017-10-10  ARGENTINA   ARGENTINA

这是我的代码:

data = get_data(DB_ENGINE, MYSQL_USER, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_PORT, MYSQL_DB, query)


if filename:
    with open(filename, 'w+') as f: f.write(json.dumps(x,default=datetime_handler))

def datetime_handler(x):
    if isinstance(x, datetime.datetime):
        #return unicode(x.strftime("%B %d, %Y"),errors="ignore")
        # return unicode(x.strftime("%B %d, %Y").encode('latin-1'),errors="ignore")
        return x.strftime("%B %d, %Y").encode('ISO-8859-1')
    else:
            return x
    raise TypeError("Unknown type")


if filename:
    with open(filename, 'w+') as f: f.write(json.dumps(x,default=datetime_handler))

我该如何解决这个问题?

修改

完整的追溯:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/usr/lib64/python2.7/json/__init__.py", line 250, in dumps
    sort_keys=sort_keys, **kw).encode(obj)
  File "/usr/lib64/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib64/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 18: invalid continuation byte

0 个答案:

没有答案