我有一张桌子的时间采用这种形式:
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']))
我收到此错误:
答案 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)