python实现统计一周内mongo某个库所有集合每天的增量,并存入表格

临时统计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是插入数据时间的时间戳

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值