在Python中更改Postgres的时间类型

时间:2019-10-19 12:27:05

标签: python postgresql datetime-format

我有一张桌子的时间采用这种形式:

2017-12-31T23:59:59.8560818Z

我不确定这实际上是什么形式。我所知道的是,我想将其在python中转换为可接受的时间类型,以便将其作为时间戳或日期插入到postgres表中(我实际上只关心日期)。除了采用日期的子字符串之外,还有什么更好的方法吗?

当我尝试这样做时:

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']))

我收到此错误:

enter image description here

1 个答案:

答案 0 :(得分:1)

  • 日期文字应该用引号引起来(否则令牌化器会感到困惑……)
  • 如果您想减少小数秒,可以使用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)