2015-10-11 71 views
1

我正在與大熊貓和SQLAlchemy將雅虎財務價格寫入SQL庫。我的問題是,如何從數據庫中刪除時間戳?pandas df.to_sql()刪除時間戳

全碼

def update (symbol): 
    engine = create_engine("sqlite:///test.db") # Access the DB Engine 
    try: 
     if not engine.dialect.has_table(engine, symbol): # If table does not exist. Create 
      start = dt.date(2000, 1, 1) 
      end = dt.datetime.today() 
      get_prices = yahoo.DataReader(symbol, 'yahoo', start, end) 
      get_prices.to_sql(symbol, engine, if_exists='append') 

此代碼的工作,它得到的價格進入一個SQL數據庫。但日期部分出現像這樣2001-01-17 00:00:00.000000

我應該如何編輯我的代碼,使時間戳不顯示?

+0

請發表您的完整信息源,請問? – hd1

+0

你使用哪個數據庫? – van

+1

默認情況下,索引('Date')的類型是'datetime64 [ns]'。爲了將它轉換爲'date',你可以在調用'get_prices.to_sql'之前執行'get_prices.index = get_prices.index.date'。 – van

回答

0

我指的是docs以及pandas to_sql,它給了我一個關於凡說什麼的想法。

下面是我整合的代碼,似乎給了我想要的。

def update (symbol): 
    engine = create_engine("sqlite:///test.db") # Access the DB Engine 
    try: 
     if not engine.dialect.has_table(engine, symbol): # If table does not exist. Create 
      start = dt.date(2000, 1, 1) 
      end = dt.datetime.today() 
      get_prices = yahoo.DataReader(symbol, 'yahoo', start, end) 
      # The below code was provided by Van, but it changes the name 
      # of the index Column to "index" instead of "date" 
      get_prices.index = get_prices.index.date 
      get_prices.to_sql(symbol, engine, if_exists='append', index=True, 
           index_label='Date') # index_label changes the name back to "Date" 

到目前爲止,這似乎給了我我的意圖。有沒有人有更好的解決方案?

+1

我認爲這是一個很好的解決方案。通過將索引設置爲新值(''get_prices.index = get_prices.index.date''),索引名稱將丟失。因此,'to_sql'對索引('index')使用'default'名稱,使用'index_label'是最簡單的方法來改變它(另一種方法是改變索引名稱本身:'get_prices.index.name = 「Date'') – joris