在 Python 中更改 Postgres 的时间类型

Changing Time Type for Postgres In Python

我有一次 table 采取这种形式:

2017-12-31T23:59:59.8560818Z

我不完全确定这到底是什么形式。我所知道的是,我想将它在 python 中转换为一种时间类型,即 acceptable 以作为时间戳或日期插入到 postgres table 中(我真的只关心日期)。有什么比只取日期的子字符串更好的方法吗?

当我尝试这个时:

exchange_rate['time'] = str(exchange_rate['time'])[:10]  #captures the YYY-MM-DD from date
exchange_rate['time'] = datetime.datetime.strptime(exchange_rate['time'], '%Y-%m-%d') #converts to datetime

cursor.execute('''INSERT INTO bitcoin VALUES ({},{})'''.format(exchange_rate['time'],exchange_rate['rate']))

我收到这个错误:

  • 日期文字应该是引号(否则分词器会混淆...)
  • 如果你想去掉小数秒,可以使用date_trunc()

CREATE TABLE bogus
        ( id integer PRIMARY KEY
        , ztimestamp TIMESTAMP WITH TIME ZONE NOT NULL
        );
INSERT INTO bogus(id,ztimestamp) VALUES
 ( 1, '2017-12-31T23:59:59.8560818Z')
,( 2, DATE_TRUNC('sec', '2017-12-31T23:59:59.8560818Z'::timestamp))
        ;

SELECT * FROM bogus;

结果:


CREATE TABLE
INSERT 0 2
 id |          ztimestamp           
----+-------------------------------
  1 | 2018-01-01 00:59:59.856082+01
  2 | 2017-12-31 23:59:59+01
(2 rows)