临时统计mongo历史数据一周内的的每天的数据情况
下面是简单代码实现
import pymongo
import datetime, time
import xlwt
conn = pymongo.MongoClient('mongodb://root:123456@localhost:27017/admin')
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
def data_write(datas):
f = xlwt.Workbook()
sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True) # 创建sheet
# 将数据写入第 i 行,第 j 列
for i in range(len(datas)):
for j in range(len(datas[i])):
sheet1.write(i, j, datas[i][j])
f.save("./news_count.xls")
def timep(day=0):
today = datetime.date.today()
if day == 0:
a = today
else:
a = today - datetime.timedelta(days=day)
return int(time.mktime(time.strptime(str(a), '%Y-%m-%d')))
def timestr(day=0):
today = datetime.date.today()
if day == 0:
a = today
else:
a = today - datetime.timedelta(days=day)
return str(a)
dbname = conn['sy_news_raw']
collections = dbname.list_collection_names(session=None)
datas = []
time_list = [timestr(i) for i in range(7, -1, -1)]
time_list.insert(0, '时间')
datas.append(time_list)
for collection in collections:
count_list = [collection]
for i in range(7, -1, -1):
pre_time = timep(i)
next_day = timep(i-1)
count = dbname[collection].find({'gtime':{"$gte":pre_time, "$lt": next_day}}).count()
count_list.append(count)
datas.append(count_list)
data_write(datas)
注意要有时间字段, 如gtime是插入数据时间的时间戳