数据帧包含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  

显示表格 struct :

  \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.astype('str')df.index转换为字符串,数据库中的index类型将是text,而to_sql是意外的!

推荐答案

将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中,将该列更改为Date:

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

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

SELECT "index", ticker, close
FROM quote;

因此,除了更改该df列的数据类型外,还应考虑更改其名称.

Python-3.x相关问答推荐

丢弃重复的索引,并在多索引数据帧中保留一个

CDKTF ec2 具有特定私有 IP 地址的娱乐

对大型数据框中的选定列进行重新排序

Sunburst 折线图可视化

try 使用 GEKKO 求解非线性方程组.系统有多种解决方案,但 GEKKO 给出了错误的解决方案.我该如何解决?

如何通过 GitLab V4 api 列出 gitlab 项目中的所有项目变量

使用 selenium 加速网页抓取

协议不支持地址系列在将 Scapy L3socket 与 WSL 一起使用时

如何融化具有自定义名称的Pandas

如何在带有 GUI 的 python 游戏中设置回答时间限制?

如何将数据框中的每一行转换为具有属性的 node ?

对齐文本文件中的列

python3:字节与字节数组,并转换为字符串和从字符串转换

Pytorch 的随机 Select ?

ValueError:预期的 2D 数组,得到 1D 数组:

无法在 Windows 8 中使用 Python 3.3 找到 vcvarsall.bat

将 args、kwargs 传递给 run_in_executor

我可以替换 Python 中对象的现有方法吗?

Python 3中星型导入的函数形式是什么

为什么 Python 生成器中的异常没有被捕获?