Python从数据库取数,对时间进行处理,统计数据汇总后画图

#-*- coding: utf8 -*-
import odbc
import numpy as np
import pylab as pl
allDate = []
allData = []
if __name__ == '__main__':
    print("run success")
    allDate, allData  =  odbc.getData()
   # print(allDate)
    pl.plot(allDate,allData)
    pl.show()
else:
    print("run error")import pymysql as mysql
import time, datetime
mysql.install_as_MySQLdb()
def getData():
    try:
        # 获取一个数据库连接,注意如果是UTF-8类型的,需要制定数据库
        conn = mysql.connect(host='xxx.xxx.xxx.xxx', user='xxx', passwd='xxx', db='xxx', port=xxx,
                             charset='utf8')
        cur = conn.cursor()  # 获取一个游标
        sql = """SELECT a.changenum,a.updatetime 
                  from xxxx a join xxxxx b 
                  on a.x = b.x 
                  where b.name = 'xxx'
                  and a.updatetime > '2017-07-01 00:00:00'
                  ORDER BY updatetime ASC"""
        cur.execute(sql)  # 游标执行sql查询语句
        data = cur.fetchall()  # fetchall()则是接收全部的返回结果行
        change_data = []
        change_date = []
        for d in data:  # 循环结果进行显示
            change_data.append(d[0])
            change_date.append(d[1])
        cur.close()  # 关闭游标
        conn.close()  # 关闭连接
    except Exception:
        print("查询失败")
    print(change_data)
    print(change_date)

    
    first_date = datetime.datetime.strptime(
        datetime.datetime.strftime(change_date[0], '%Y-%m-%d %H:%M:%S')[0:10] + " 00:00:00", '%Y-%m-%d %H:%M:%S')
    # 获取第一个时间数据,取得日期部分,向前
    last_date = datetime.datetime.strptime(
        datetime.datetime.strftime(change_date[len(change_date) - 1], '%Y-%m-%d %H:%M:%S')[0:10] + " 00:00:00",
        '%Y-%m-%d %H:%M:%S') + datetime.timedelta(days=1)
    # 获取最后一个时间数据,取得日期部分,向后
    # print(first_date)
    # print(last_date)
    date = []
    data = []
    temp_date = first_date
    n = 0
    num = 0
    #外层循环,每次增加半小时
    while temp_date < last_date:
        for i in range(n, len(change_date)):
            #内层循环,循环数据库数据,在该半小时之内的变换情况
            if temp_date <= change_date[i] < temp_date + datetime.timedelta(minutes=30):
                num += change_data[i]
            else:
                break
        data.append(num)  # 对变化情况进行记录以便于后续画图的Y轴数据
        num = 0
        n = i
        temp_date = temp_date + datetime.timedelta(minutes=30)  # 横轴时间数据
        date.append(temp_date)

    print(len(date))
    print(len(data))
    print(date)
    print(data)
    return  date, data  # 因为未对齐到外层的getData()主函数,曾经导致出错

你可能感兴趣的:(数据处理)