千家信息网

Python 统计时间内的并发数

发表于:2024-09-23 作者:千家信息网编辑
千家信息网最后更新 2024年09月23日,# coding:utf-8# 1.导入模块# datatime模块用于定义时间及时间的加减操作# MySQLdb模块用于Python2.0连接数据库,Python3.0连接数据库使用pymysql#
千家信息网最后更新 2024年09月23日Python 统计时间内的并发数
# coding:utf-8# 1.导入模块# datatime模块用于定义时间及时间的加减操作# MySQLdb模块用于Python2.0连接数据库,Python3.0连接数据库使用pymysql# xlwt模块是excel操作模块,用于将数据写入excel中import datetimeimport MySQLdbimport xlwt# 2.连接数据库,获取数据# MySQLdb.connect用于定义连接数据库的属性# myconn.cursor()定义游标对象# query_sql定义查询的语句# mycursor.execute()执行查询语句,仅仅是执行语句,不输出结果。# mycursor.fetchall()提取查询数据。all全部数据,one单条数据,many取多少条数据。fetchmany(10)取10条数据。# mycursor.close()关闭游标# myconn.close()关闭连接myconn = MySQLdb.connect(host='1',user='wn',passwd='9eu',db='bs',charset='utf8')mycursor = myconn.cursor()query_sql = '''select JOIN_TIME,LEAVE_TIME from commfee where JOIN_TIME between '2019-12-24 15:00:00' and '2019-12-24 15:30:00' '''mycursor.execute(query_sql)sql_result = mycursor.fetchall()mycursor.close()myconn.close()# 3.定义全局参数# sum1 = []定义列表sum1,sum1用于生成比较的时间列表# sum2 = []定义列表sum2,sum2用于生成并发数的列表sum1 = []sum2 = []# 4.定义数据筛选函数# compare_time 比较时间,最开始值取开始时间的第一个值。# start_time = [sql_result[i][0] for i in range(0,len(sql_result))]将查询到的结果拆分为两个列表start_time和end_time。# compare_time < start_time[len(sql_result)-1],compare_time时间和start_time列表中的时间比较# compare_time += datetime.timedelta(seconds=1),每次比较后,compare_time时间+1# datetime.timedelta(seconds=1),timedelta(seconds=1)时间变化1s# sum1.append(compare_time),将得到的compare_time写入sum1列表中。def query_data():    compare_time = sql_result[0][0]    start_time = [sql_result[i][0] for i in range(0,len(sql_result))]          end_time = [sql_result[i][1] for i in range(0,len(sql_result))]    while compare_time < start_time[len(sql_result)-1]:          compare_time += datetime.timedelta(seconds=1)                    count1 = 0                   count2 = 0          for time1 in start_time:                          if time1 <= compare_time:                                   count1 = count1 + 1                           for time2 in end_time:                                          if time2 <= compare_time:                                     count2 = count2 - 1                           sum1.append(compare_time)                    sum2.append(count1+count2)# 5.定义excel操作函数# xlwt.Workbook(encoding='utf-8')定义编码格式# wbk.add_sheet('My worksheet')定义操作的sheet表# xlwt.XFStyle()定义单元格格式# datastyle.num_format_str = 'yyyy-mm-dd hh:mm:ss'定义单元格中数据格式# worksheet.write(row,0,sum1[row],datastyle) 按定义的格式写入数据# wbk.save()保存操作的excel表格。def re_sheet():                wbk = xlwt.Workbook(encoding='utf-8')    worksheet = wbk.add_sheet('My worksheet')    datastyle = xlwt.XFStyle()    datastyle.num_format_str = 'yyyy-mm-dd hh:mm:ss'    for row in range(0,len(sum1)):                 worksheet.write(row,0,sum1[row],datastyle)                    worksheet.write(row,1,sum2[row])              wbk.save('Concurrency.xls')    query_data()     re_sheet()
0