代码之家  ›  专栏  ›  技术社区  ›  showkey

如何将日期时间索引写入日期类型的表中?

  •  0
  • showkey  · 技术社区  · 3 年前

    数据帧包含一个索引,其dytpe为 datetime64[s]

    df
               ticker   close
    2008-01-28   aacg  0.7380
    2008-01-29   aacg  0.6797
    2008-01-30   aacg  0.6603
    2008-01-31   aacg  0.7418
    2008-02-01   aacg  0.7387
    

    编写 df 进入表格 quote :

    df.to_sql('quote',con=engine,index=True)
    

    在postgresql中显示记录:

    select * from quote;
    
            index        | ticker | close  
    ---------------------+--------+--------
     2008-01-28 00:00:00 | aacg   |  0.738
     2008-01-29 00:00:00 | aacg   | 0.6797
     2008-01-30 00:00:00 | aacg   | 0.6603
     2008-01-31 00:00:00 | aacg   | 0.7418
     2008-02-01 00:00:00 | aacg   | 0.7387  
    

    显示表格结构:

      \d quote
                             Table "public.quote"
     Column |            Type             | Collation | Nullable | Default 
    --------+-----------------------------+-----------+----------+---------
     index  | timestamp without time zone |           |          | 
     ticker | text                        |           |          | 
     close  | double precision            |           |          | 
    Indexes:
        "ix_quote_index" btree (index)
    

    如何使记录写成以下格式和索引的格式 date ?

      index      | ticker | close  
    ------------+--------+--------
     2008-01-28  | aacg   |  0.738
     2008-01-29  | aacg   | 0.6797
     2008-01-30  | aacg   | 0.6603
     2008-01-31  | aacg   | 0.7418
     2008-02-01  | aacg   | 0.7387  
    

    如果我转换 df.index 转换为字符串 df.index.astype('str') 这个 index 数据库中的类型为 text 什么时候 to_sql ,不应为!

    1 回复  |  直到 3 年前
        1
  •  1
  •   Adrian Maxwell    3 年前

    将df时间戳列更改为日期:

    # Convert index to date data type
    df.index = df.index.date
    
    df.to_sql('quote', con=engine, index=True, index_label='idx_quote_index')
    

    或者,在Postgres中,将列更改为日期:

    ALTER TABLE quote 
    ALTER COLUMN index TYPE date 
    USING index::date;
    

    我不建议在任何SQL数据库中将“index”作为列名——它是SQL中的保留关键字,因此每当在查询中引用它时,都需要将其用双引号括起来。例如:

    SELECT "index", ticker, close
    FROM quote;
    

    因此,除了更改df列的数据类型外,还可以考虑更改其名称。