find()函數(shù)的進(jìn)階用法
- find 函數(shù)中各參數(shù)與SQL語(yǔ)法的對(duì)照:
table.find( { 'key': value }, { column1: 1, column2: 1 } )
用SQL寫就是:
select column1替蛉, column2
from table
where key = value
源碼
- getdaterange() 接收入?yún)⒎謩e為起润绎,止日期悉患,輸出一個(gè)日期列表列出所有在給定起烫映,止時(shí)間范圍之間的日期叮称,格式為‘2016-07-10’酣藻。
- get_statistic_by_daterange() 接收data參數(shù)為從數(shù)據(jù)表查詢某一類商品的結(jié)果舒萎,反回此類商品在給定日期范圍內(nèi)每天的發(fā)貼數(shù)量程储,以list格式返回。
def getdaterange(startfrom, enddate):
# input: ('2016-01-01', '2016-01-07')
# ouput: ['2016-01-01', '2016-01-02', '2016-01-03', '2016-01-04', '2016-01-05', '2016-01-06', '2016-01-07']
stastamp = time.mktime(time.strptime(startfrom,"%Y-%m-%d"))
endstamp = time.mktime(time.strptime(enddate,"%Y-%m-%d"))
datelist = []
for i in range(int((endstamp - stastamp)/3600/24)):
datelist.append(time.strftime("%Y-%m-%d", time.localtime(stastamp + i*3600*24)))
return datelist
def get_statistic_by_daterange(data, daterange):
# input: data = {}, daterange = ['2016-07-02', '2016-07-03', '2016-07-04', '2016-07-05', '2016-07-06', '2016-07-07', '2016-07-08']
# ouput: {'2016-07-07': 15, '2016-07-04': 7, '2016-07-02': 35, '2016-07-08': 36, '2016-07-06': 13, '2016-07-05': 10, '2016-07-03': 9}
statistic = {}
for time in daterange:
statistic[time] = 0
for item in data:
itdate = item['pubtime'][0]
if itdate in daterange:
statistic[itdate] += 1
print(statistic)
return [item[1] for item in sorted(statistic.items())]#.values()
- 起始日期以當(dāng)前日期為參考的7天前,
終止日期為當(dāng)前日期章鲤,
分別獲取指定的三種類別的所有貼子數(shù)據(jù)摊灭,用get_statistic_by_daterange()分別算出它們的最近7日的發(fā)貼量
stadate = time.strftime("%Y-%m-%d", time.localtime(time.time() - 7 * 3600 * 24 ))
enddate = time.strftime("%Y-%m-%d", time.localtime(time.time()))
datelist = getdaterange(stadate, enddate)
print(datelist )
for item in ['筆記本電腦', '手機(jī)', '臺(tái)式電腦整機(jī)']:
datalist.append(get_statistic_by_daterange(tinfo.find({'category': item}), datelist))
#print(data)
運(yùn)行結(jié)果
-
指定的三類商品最近7天的發(fā)貼量統(tǒng)計(jì)