UnicodeDecodeErro

# -*-coding:utf-8-*-
# !/usr/bin/env python
import json
import datetime
import time, sys
from pymongo import MongoClient

db = MongoClient('mongodb://192.168.88.xx:27017').tal

# start_date = sys.argv[1]
# end_date = sys.argv[2]
start_date = '2017-11-17 00:00:00 000'
end_date = '2017-11-18 00:00:00 000'
starts = [start_date, end_date]

for index, day in enumerate(starts):
    if (index == len(starts) - 1):
        break
    else:
        start = datetime.datetime.strptime(day, '%Y-%m-%d %H:%M:%S %f')
        end = datetime.datetime.strptime(starts[index + 1], '%Y-%m-%d %H:%M:%S %f')
        ress = db.sysRequestWrapper.find({"account": {"$exists": True },"staCode": {"$exists": True },"requestTime":{"$gte":start,"$lte":end}})
        for res in ress:
            en_type = 'None'
            keys = []
            account = res['account']
            staCode = res['staCode']
            requestTime = res['requestTime']
            reParamsObj = json.dumps(res['reParamsObj'], sort_keys=True)
            uri = res['uri']

            bodyEntype = 'none'
            if (account not in ('NULL', '', 'account', 'identification.bank.accountTwo') and uri not in ('/error')):
                print '%s\t%s\t%s\t%s\t%s\t%s\t%s' % (account, uri,requestTime, reParamsObj, staCode, bodyEntype, en_type)

执行python脚本重定向时出现如下错误

upsmart@upsmart-12:~/桌面$ python talserver.py >1.csv
Traceback (most recent call last):
  File "talserver.py", line 37, in <module>
    print '%s\t%s\t%s\t%s\t%s\t%s\t%s' % (account, uri,requestTime, reqParams, staCode, bodyEntype, en_type)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 121: ordinal not in range(128)

两种解决方案:
1)
import time, sys
reload(sys)
sys.setdefaultencoding(‘utf8’)

2)
requestTime = res[‘requestTime’].strftime(’%Y-%m-%d %H:%M:%S %f’)
result = [account, uri,requestTime, reqParams, staCode, bodyEntype, en_type]
print(",".join(result).encode(‘utf-8’).strip())

这里注意要把时间转换成string类型,不然会报错:
print(",".join(result).encode(‘utf-8’).strip())
TypeError: sequence item 2: expected string or Unicode, datetime.datetime found

第二种方法更好一些

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值