需要将unix转换为日期,但某些值已经是日期格式

时间:2018-02-23 21:02:57

标签: sql postgresql

我有一个字段被推入我的数据库,其中90%的值是毫秒-unix时间戳,但约5%的值为null,5%是实际日期戳,但该字段是文本字段。

我正在尝试使用此转换日期:

cast(to_timestamp(cast(date_field as bigint)/1000) as date)

问题是已经是时间戳的日期字段(以文本字段格式)让我搞砸了,因为它们无法转换为bigint。像这样的所有值都以“2016-”开头,所以我提出了一个查询来排除它们,但它们仍然存在。

要排除这些的查询:

Select distinct
date
from table1
where date<>'2016%'

其中一个结果值:

2016-11-04 02:23:10

2 个答案:

答案 0 :(得分:1)

你可以做到 类似的东西:

where date like '20%' --for years after 2000 (there isnt yet a unix timestimp that starts with 2 )
or date like '19%' (there isnt yet a unix timestimp that starts with 19 )

答案 1 :(得分:1)

因此,您可以将时间转换为毫秒,如日期:

SELECT FROM_UNIXTIME(t.date/1000,'%Y-%m-%d %H:%i:%s') FROM table1 t WHERE t.date NOT LIKE '2016-%' AND t.date IS NOT NULL;