python读取sqlserver数据,并保存到csv中

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010082526/article/details/83993579

# -*- coding: utf-8 -*-
"""
@use:查询17.11-18.1,18.6-18.8的PM2.5数据,导出到csv
"""
import pymssql
import xlwt
import datetime

from xml.dom.minidom import parse 

def do(): 
    try:
        doc=parse('baseinfo.xml')
        login=doc.getElementsByTagName("login")[0]
        ip=login.getAttribute("ip")
        user=login.getAttribute("user")
        password=login.getAttribute("password")
        database=login.getAttribute("database")
        
        timerange=doc.getElementsByTagName("timerange")[0]
        start=timerange.getAttribute("start")
        end=timerange.getAttribute("end")  
        
        start1 =datetime.datetime.strptime(start, '%Y-%m-%d %H:%M:%S')
        end1 = datetime.datetime.strptime(end, '%Y-%m-%d %H:%M:%S')
        theHour=int((end1-start1).days*24 + (end1-start1).seconds/3600)+1
        print(theHour)
    
            
        conn=pymssql.connect(host=ip,user=user,password=password,database=database)
        #查看连接是否成功
        cursor = conn.cursor()
        #    sql = "select a.STATIONCODE,a.MONIDATE,b.LONGITUDE,b.LATITUDE,a.PM25  from T_MON_AIRSTATIONHOUR a  join T_BAS_AIRSTATION b  on a.STATIONCODE=b.STATIONCODE where MONIDATE='2018-09-21 15:00:00.000'"
        #日期区间数据查询
        #sql = "select a.STATIONCODE,a.MONIDATE,b.LONGITUDE,b.LATITUDE,a.PM25  from T_MON_AIRSTATIONHOUR a  join T_BAS_AIRSTATION b  on a.STATIONCODE=b.STATIONCODE where MONIDATE>='"+start+"' and MONIDATE<='"+end+"'"
        
        for h in range(theHour):
            monidate=(start1 + datetime.timedelta(hours=h)).strftime('%Y-%m-%d %H:%M:%S')
            #        print(monidate)
            #单个时间数据查询
#            sql = "select a.STATIONCODE,a.MONIDATE,b.LONGITUDE,b.LATITUDE,a.PM25  from T_MON_AIRSTATIONHOUR a  join T_BAS_AIRSTATION b  on a.STATIONCODE=b.STATIONCODE where MONIDATE='"+monidate+"'"
            sql="select a.ID,a.RecordTime,b.LNG1,b.LAT1,a.PM25 from T_MIC_DATAAIR a  join T_MIC_STATION b  on a.ID=b.ID where b.STATIONTYPE='2' and a.RecordTime='"+monidate+"'"
            #时间列,转换成 2018-09-21T15:00:00  格式
            str_date=str(datetime.datetime.strptime(str(monidate), "%Y-%m-%d %H:%M:%S") )
            str_date=str_date[0:10]+'T'+str_date[-8:] 
            cursor.execute(sql)
            #用一个rs变量获取数据
            rs = cursor.fetchall()
            #创建文件
            file = xlwt.Workbook()
            #写入sheet名称,2017-05-01T06_00_00  格式
            name_sheet=str_date[0:10]+'T'+str_date[-8:-6]+'_00_00'
            table = file.add_sheet(name_sheet)
        
            title=['deviceid','date','lon','lat','pm25']
            #table.write(行_0开始, 列_0开始, 值)
            #写入表头,第一行
            for j in range(5):
                table.write(0, j, title[j])
            #index_i+1 行,index_j列
            for index_i,r in enumerate(rs):
                for index_j,val in enumerate(r):
                    if index_j== 1:
                        
                        val1=str(datetime.datetime.strptime(str(val), "%Y-%m-%d %H:%M:%S") )
                        str1=val1[0:10]+'T'+val1[-8:]
                        table.write(index_i+1, index_j, str1)
        #                '2018-09-21T15:00:00'
                    else:
                        table.write(index_i+1, index_j, val)
            #保存文件,2018-09-21T15_00_00.csv 名称格式
            name_file=name_sheet+'.csv'
            file.save(name_file)

    except Exception as e:
        print(e)
        cursor.close() 
        conn.close()
        return
    
    cursor.close() 
    conn.commit()      
    conn.close() 
            
    

if __name__ == '__main__':

     do()

Python3操作SQL Server数据库(实例讲解)

https://www.jb51.net/article/126414.htm

1.xlwt

 

#输出数据

# for r in rs:

# print(len(r))

# for str in r:

# print(str)

# print(rs)

 

  1. python Excel数据读取与写入

import xlwt

 

file = xlwt.Workbook()

 

table = file.add_sheet('sheet name')

for i in range(10):

    table.write(i, 0, i)

 

file.save('xls_save.xls')

https://blog.csdn.net/qq_35451572/article/details/80427960

 

3.python for循环访问数组下标

http://outofmemory.cn/code-snippet/3741/accessing-the-index-in-python-for-loops

但是有时候我们会需要在便利数组的同时访问下标,这时候可以借助于enumerate函数来实现,例如:

l = [1,2,3]for index,val in enumerate(l):

    print 'index is %d, val is %d' % (index,val)

#输出下标

# for index_i,r in enumerate(rs):

# print(index_i)

# for index_j,str in enumerate(r):

# print(index_j)

 

4.Python if 语句

http://www.runoob.com/python3/python3-if-example.html

以下实例通过使用 if...elif...else 语句判断数字是正数、负数或零:

实例(Python 3.0+)

 num = float(input("输入一个数字: ")) 

if num > 0: print("正数") 

elif num == 0: print("") 

else: print("负数")

  1. 日期格式转换及截取字符串

日期最终格式是

2018-09-21T15:00:00

a】Python 日期格式转换

times = time.strftime("%H.%M", time.strptime(time_string, formats)) #将时间转为hh.mm类型 

ftime = datetime.datetime.strptime(times, "%H.%M") #将times字符串转为%H.%M的datetime类型

 

datetime.datetime.strptime(str(val), "%Y-%m-%d %H:%M:%S")

【b】python中的字符数字之间的转换函数

https://www.cnblogs.com/wuxiangli/p/6046800.html

str(x )                 将对象 x 转换为字符串   

c】截取字符串

https://www.cnblogs.com/huangcong/archive/2011/08/29/2158268.html

str = ’0123456789′
print str[0:3] #截取第一位到第三位的字符
print str[:] #截取字符串的全部字符
print str[6:] #截取第七个字符到结尾
print str[:-3] #截取从头开始到倒数第三个字符之前
print str[2] #截取第三个字符
print str[-1] #截取倒数第一个字符
print str[::-1] #创造一个与原字符串顺序相反的字符串
print str[-3:-1] #截取倒数第三位与倒数第一位之前的字符
print str[-3:] #截取倒数第三位到结尾
print str[:-5:-3] #逆序截取,具体啥意思没搞明白?

 

【d】Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)

https://www.cnblogs.com/exusll/p/6393621.html?utm_source=tuicool&utm_medium=referral

【5】  TypeError: 'datetime.datetime' object is not subscriptable

报错行:  str1=val1[0:10]+'T'+val1[-8:]

    for index_i,r in enumerate(rs):

        for index_j,val in enumerate(r):

            if index_j== 1:

                

                val1=str(datetime.datetime.strptime(str(val), "%Y-%m-%d %H:%M:%S") )

                str1=val1[0:10]+'T'+val1[-8:]

                table.write(index_i+1, index_j, str1)

  1. 读取配置文件

from xml.dom.minidom import parse

【1】连接数据库

    conn = pymssql.connect(host='.',

                user='sa',

                password='123456',

                database='AirDB_CC',

                charset='utf8')

改成

doc=parse('baseinfo.xml')

    login=doc.getElementsByTagName("login")[0]

    ip=login.getAttribute("ip")

    user=login.getAttribute("user")

    password=login.getAttribute("password")

database=login.getAttribute("database")

conn=pymssql.connect(host=ip,user=user,password=password,database=database)

【2】读取日期

    <timerange start="2018-09-13 06:00" end="2018-09-13 08:00"></timerange>

 

        timerange=doc.getElementsByTagName("timerange")[0]

        start=timerange.getAttribute("start")

        end=timerange.getAttribute("end")  

【3】计算小时差

【a】

https://blog.csdn.net/u012062455/article/details/73287023/

secondsDiff=(dataTimea-dataTimeb).seconds

【b】

[Python3]显示当前时间、计算时间差以及时间加减法

https://blog.csdn.net/asher117/article/details/83012803

【c】

Python3基础知识之日期时间与字符的转换

http://www.cnblogs.com/johsan/p/9046406.html

【d】

python 日期格式和字符串格式的转化

https://www.cnblogs.com/he0xff/p/8479499.html

【e】

Python学习笔记 --- 循环遍历时间区间

https://blog.csdn.net/u012965373/article/details/78060533

 

    start1 =datetime.datetime.strptime(start, '%Y-%m-%d %H:%M:%S')

    end1 = datetime.datetime.strptime(end, '%Y-%m-%d %H:%M:%S')

print(int((end1-start1).seconds/3600))

【4】遍历小时

theHour=int((end1-start1).seconds/3600)+1

print(theHour)

for h in range(theHour):

monidate=(start1 +datetime.timedelta(hours=h)).strftime('%Y-%m-%d %H:%M:%S')

print(monidate)

输出:

3

2018-09-13 06:00:00

2018-09-13 07:00:00

2018-09-13 08:00:00

 

【5】try

 

 

  1. (end1-start1).seconds跨越天数的情况

        theHour=int((end1-start1).days*24 + (end1-start1).seconds/3600)+1

        print(theHour)

  1. 日数据导出到csv

 

day = begin + datetime.timedelta(days=i)

 

T_MIC_DATAAIRDAY  日数据表

<timerange start="2018-06-01 00:00:00" end="2018-08-31 23:00:00"></timerange>

【1】time data '2018-06-01' does not match format '%Y-%m-%d %H:%M:%S'

monidate=(start1 + datetime.timedelta(days=h)).strftime('%Y-%m-%d %H:%M:%S')

改成

            monidate=(start1 + datetime.timedelta(days=h)).strftime('%Y-%m-%d')

【2】time data '2018-06-01' does not match format '%Y-%m-%d %H:%M:%S'

str_date=str(datetime.datetime.strptime(str(monidate), "%Y-%m-%d %H:%M:%S") )

            str_date=str_date[0:10]+'T'+str_date[-8:]

改成

str_date=str(monidate)[0:10]+'T'+'00:00:00'

 

【3】time data '2018-06-01' does not match format '%Y-%m-%d %H:%M:%S'

val1=str(datetime.datetime.strptime(str(val), "%Y-%m-%d %H:%M:%S") )

                        str1=val1[0:10]+'T'+val1[-8:]

                        table.write(index_i+1, index_j, str1)

改成

table.write(index_i+1, index_j, str_date)       

 

猜你喜欢

转载自blog.csdn.net/u010082526/article/details/83993579