如何从MS SQL Server数据库将数据加载到numpy数组中

时间:2019-06-18 08:51:44

标签: python sql sql-server numpy

我希望将数据从SQL Server加载到numpy数组。

例如:SQL Server中有一个名为x的表,我需要将“ duration”列下的详细信息提取到numpy数组中。

我需要将它们按周划分,将它们存储在4个不同的numpy数组中,例如:每个数组应包含该特定星期的duration列中的详细信息,因此以这种方式,4个不同的numpy数组应包含4个不同周的详细信息。

我正在尝试将值粘贴到Excel工作表上。和值应自动填充。

import pyodbc
import pandas as pd
from datetime import datetime, timedelta

LastDayofCWMinusone = datetime.now().date()-timedelta(days=2)
startofCWMinusone = lastDayofCWMinusone - timedelta(days=((lastDayofCWMinusone.weekday()+1)%7))
endofCWMinusone = startofCWMinusone +timedelta(days=6)
LWDateRange = startofCWMinusone.strftime('%m/%d/%Y') + '-' + endofCWMinusone.strftime('%m/%d/%Y')
ws1['C1'] = LWDateRange

#Get CW-2 and update G1
startofCWMinustwo = startofCWMinusone - timedelta(days=7)
endofCWMinustwo = endofCWMinusone - timedelta(days=7)
LWMinustwoRange = startofCWMinustwo.strftime('%m/%d/%Y') + '-' + endofCWMinustwo.strftime('%m/%d/%Y')
ws1['G1'] = LWMinustwoRange


#Get CW-3 and update K1
startofCWMinusthree = startofCWMinustwo - timedelta(days=7)
endofCWMinusthree = endofCWMinustwo - timedelta(days=7)
LWMinusthreeRange = startofCWMinusthree.strftime('%m/%d/%Y') + '-' + endofCWMinusthree.strftime('%m/%d/%Y')
ws1['K1'] = LWMinusthreeRange

#Get CW-4 and update O1
startofCWMinusfour = startofCWMinusthree - timedelta(days=7)
endofCWMinusfour = endofCWMinusthree - timedelta(days=7)
LWMinusfourRange = startofCWMinusfour.strftime('%m/%d/%Y') + '-' + endofCWMinusfour.strftime('%m/%d/%Y')
ws1['O1'] = LWMinusfourRange

conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=servername;DATABASE=databasename;UID=uidname;PWD=password')

sSQL = "select * from x where businessmodified>='{} 00:00:00' and businessmodified<='{} 23:59:59'".format(startofCWMinusfour.strftime('%m-%d-%Y'),endofCWMinusone.strftime('%m-%d-%Y'))

x = pd.read_sql(sSQL,conn,index_col=None)
x['Week_Number'] = x['businessmodified'].dt.week

0 个答案:

没有答案