我编写了一个简单的 python 应用程序来使用 pandas_datareader 从谷歌读取股票价格并将它们存储在数据库中。我觉得奇怪的是,当我编写数据集时,日期是正确的,但是当我提取日期并在更新语句中使用它时,日期就搞砸了。这是我的代码(不包括导入语句和逻辑)和结果:
df = webd.DataReader('WTB.L', 'google', dtStart, dtEnd)
print(df.head())
开高低收盘量 日期 2012-03-02 1687.0 1687.0 1672.0 1672.0 341944 2012-03-05 1666.0 1684.0 1660.0 1665.0 333824
lastPriceDateX = pd.to_datetime(df['Date'].tail(1).item())
lastPriceDateY = lastPriceDateX
lastPriceDate = lastPriceDateY.strftime('%d-%m-%Y').isoformat()
print('Last Price Date {}'.format(lastPriceDate))
最后价格日期 21-03-2017
到目前为止看起来不错,日期格式正是我想要的!现在我将日期写入 SQLITE 数据库:日期存储为 -1999
数据集被写入 SQLite 数据库,它具有正确的日期格式:
“12667” “2017-03-16 00:00:00” “WTB.L” “3926.0” “3936.0” “3882.0” “3909.0” “441329”
“12668” “2017-03-17 00:00:00” “WTB.L” “3908.0” “3926.0” “3892.0” “3903.0” “642291”
“12669” “2017-03-20 00:00:00” “WTB.L” “3907.0” “3917.0” “3883.32” “ 3916.0""175681""12670"
"2017-03-21 00:00:00""WTB.L""3921.0""3926.0""3888.0""3914.0""315763"
编写此数据集的代码:
df.to_sql('tblStockPricesGoogle', conn,
if_exists='append', index=False,
index_label=None, chunksize=None, dtype=None)
我可以编写一个 python 函数来从价格表中获取最新日期并将其写入最新价格。但是,我想了解为什么此日期打印正确但未正确写入数据库。
非常感谢大家。
更多代码:
#Gets data from google.
try:
print('Try')
df = webd.DataReader('WTB.L', 'google', dtStart, dtEnd)
print(df.head())
df.insert(0,"Symbol", sy)
df = df.reset_index()
if df.empty :
print('DataFrame is empty. There could be various issues. No updates.')
else :
print(df.head(1))
print("Starting update:")
#Call update function and pass dataframe.
if sql3.saveDFtoSQL(df):
#update table with last price, date, updated date etc.
index is also returned.
lastPrice = df['Close'].tail(1).item()
lastPriceDateX = pd.to_datetime(df['Date'].tail(1).item())
lastPriceDateY = lastPriceDateX
lastPriceDate = lastPriceDateY.strftime('%d-%m-%Y')
print("Updated {} prices, task done!".format(sy))
print('Last Price {}'.format(lastPrice))
print('Last Price Date {}'.format(lastPriceDate))
lastUpdate = dt.date(today.year,today.month,today.day).isoformat()
print('LastUpdate attribute:',lastUpdate)
sql3.updateListLastUp(sy,lastUpdate,lastPrice,lastPriceDate)
def updateListLastUp(symbol,date,lastPrice,lastPriceDate):
try:
strUpdate = 'UPDATE tblList SET lastUpdate="{}", LastPrice={},LastPriceDate={}, GetData=0 WHERE Ticker="{}"'.format(date,lastPrice,lastPriceDate,symbol)
conn = sq3.connect(sql_file)
conn.execute(strUpdate)
conn.commit()
return 'Done'
except sq3.Error as er:
print('Failure to update DataSet:', er)
return er.tostring()