我正在尝试从包含 json 转储的 CSV 文件中获取一些数据到我的 postgres 数据库中。只要它只是字符串就没问题,但我希望包含时间戳的字符串作为时间戳存储在 postgres 中。所以我需要对这两个字段进行一些转换:registerdate 和 dateofbirth。除了日期转换行之外,下面的代码有效......
关于如何将两个字符串成功转换为时间戳的任何线索如下:
CREATE TABLE users (
id SERIAL,
mongo_id TEXT,
password VARCHAR(128),
firstname VARCHAR(200),
lastname VARCHAR(200),
dateofbirth TIMESTAMP,
registerdate TIMESTAMP,
displayname VARCHAR(200),
language VARCHAR(200),
country VARCHAR(200),
profilepicture VARCHAR(200),
backgroundpicture VARCHAR(200),
type VARCHAR(200),
sex VARCHAR(6),
offlinemode BOOLEAN,
email VARCHAR(200),
friends VARCHAR(255)[]
);
INSERT INTO users (mongo_id, password,firstname,lastname, dateofbirth, registerdate, displayname, language)
SELECT data->>'_id',
data->>'password',
data->>'firstName',
data->>'secondName',
to_timestamp(data->'dateOfBirth'->>'$date'), /*<------*/
to_timestamp(data->'registerDate'->>'$date'), /*<-------*/
data->>'displayName',
data->>'language'
FROM import.mongo_users;
mongo_users中的数据格式:
{ "_id" : "1164", "password" : "aaa123123", "firstName" : "Adam", "secondName" : "Kowlalski", "dateOfBirth" : { "$date" : "2014-05-18T07:41:09.202+0200" }, "registerDate" : { "$date" : "2016-06-01T12:59:53.941+0200" }, "displayName" : "Adam Kowlalski", "language" : "nb", "country" : null, "profilePicture" : null, "backgroundPicture" : null, "type" : "USER", "sex" : "MALE", "offlineMode" : true, "email" : "bk_1164@test.email", "friends" : [ "KUE" ] }
最佳答案
to_timestamp
函数需要两个参数:文本格式的 date_time 和格式化模板。
您不需要使用 to_timestamp,因为您的日期时间值已经使用有效的时间戳格式化,并且 PostgreSQL 非常了解 json 格式的时间戳。以下效果很好:
SELECT data->>'_id',
data->>'password',
data->>'firstName',
data->>'secondName',
(data->'dateOfBirth'->>'$date')::timestamp, --<< simply cast to timestamp
(data->'registerDate'->>'$date')::timestamp, --<< simply cast to timestamp
data->>'displayName',
data->>'language'
FROM (SELECT
'{ "_id" : "1164", "password" : "aaa123123", "firstName" : "Adam", "secondName" : "Kowlalski", "dateOfBirth" : { "$date" : "2014-05-18T07:41:09.202+0200" },
"registerDate" : { "$date" : "2016-06-01T12:59:53.941+0200" }, "displayName" : "Adam Kowlalski", "language" : "nb", "country" : null, "profilePicture" : null,
"backgroundPicture" : null, "type" : "USER", "sex" : "MALE", "offlineMode" : true, "email" : "bk_1164@test.email", "friends" : [ "KUE" ] }'::jsonb as data) d
关于json - postgres json解析为时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37652695/