# -*-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
第二种方法更好一些