【问题标题】:postgres convert a substring to epochpostgres 将子字符串转换为纪元
【发布时间】:2017-11-28 16:38:58
【问题描述】:

我正在尝试在单个查询中将纪元时间戳转换为人类可读的时间戳,但我有点卡住了 - 感谢任何帮助。

testing=# SELECT creation_time FROM users LIMIT 1;
    creation_time    
---------------
 1354006445722
(1 row)

testing=# SELECT SUBSTRING('1498123813330', 1,10);
  SUBSTRING  
------------
 1498123813
(1 row)

testing=# SELECT TIMESTAMP WITH TIME ZONE 'epoch' + 1498123813 * INTERVAL '1 second';
        ?column?        
------------------------
 2017-06-22 02:30:13-07
(1 row)

无论如何要把它放到一个查询中?

【问题讨论】:

  • created_time 是否存储为文本?
  • @McNets 'header_timestamp'
  • @OtoShavadze - 抱歉,现在更新。

标签: sql postgresql substring epoch


【解决方案1】:

你想要的是CASTing,即

SELECT TIMESTAMP WITH TIME ZONE 'epoch' +
         SUBSTRING(creation_time, 1, 10)::NUMERIC * INTERVAL '1 second';

但是,如果创建时间是纪元毫秒,你可以这样做:

SELECT to_timestamp(creation_time::double precision / 1000)

相反,它也会保留毫秒。如果您想要一种格式,您可以使用to_char 打印出时间戳,而不是默认的时间戳输出。

http://rextester.com/EHPNJ86308

【讨论】:

  • 尝试这个时我得到No function matches the given name and argument types. You might need to add explicit type casts.
【解决方案2】:

假设created_time 存储为varchar,您可以对其应用相同的substring 逻辑并将其转换为数字:

SELECT TIMESTAMP WITH TIME ZONE 'epoch' + 
       SUBSTRING(creation_time, 1,10)::NUMERIC * INTERVAL '1 second'
FROM   users

【讨论】:

  • 尝试这个时我得到No function matches the given name and argument types. You might need to add explicit type casts.
  • creation_time是什么类型?
  • 类型:header_timestamp
猜你喜欢
  • 1970-01-01
  • 2016-07-23
  • 2012-04-03
  • 2013-01-25
  • 2018-09-07
  • 2018-02-18
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
相关资源
最近更新 更多