[英]Writing a date from a pandas_datareader to database results in -1999
我编写了一个简单的python应用程序,使用pandas_datareader从Google读取股票价格并将其存储在数据库中。 我感到奇怪的是,当我编写数据集时,日期是正确的,但是当我提取日期并将其用于更新语句中时,日期就混乱了。 这是我的代码(不包括导入语句和逻辑)和结果:
df = webd.DataReader('WTB.L', 'google', dtStart, dtEnd)
print(df.head())
Open High Low Close Volume Date 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()
在:
strUpdate = 'UPDATE tblList SET lastUpdate="{}", LastPrice={},LastPriceDate={}, GetData=0 WHERE Ticker="{}"'.format(date,lastPrice,lastPriceDate,symbol)
您正在使用字符串插值法(这是一个很大的假步骤,因为它不安全,并且如果没有适当地转义值也会导致令人惊讶的结果)来构造查询字符串,因此数据库引擎看到的是“ 2017-03-15”被解释为2017-3-15并计算值为1999等...
如果使用查询参数,所有问题都将消失,例如:
strUpdate = 'update tblList set lastUpdate=?, lastPrice=?, lastPriceDate=?, GetData=0 where Ticker=?'
# ...
conn.execute(strUpdate, (date, lastPrice, lastPriceDate, symbol))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.