如何在PostgreSQL中将unix时间戳列转换为日期格式?
我试图从unixtimestamp列中获得yyyy-mm-dd格式的结果,但得到的是yyyy-mm-dd hh:mm:ss 我在接收时间列中的数据如下:如何在PostgreSQL中将unix时间戳列转换为日期格式?,postgresql,Postgresql,我试图从unixtimestamp列中获得yyyy-mm-dd格式的结果,但得到的是yyyy-mm-dd hh:mm:ss 我在接收时间列中的数据如下: recieve_time 1557866863 | 1557866863 | 1557866863 | 1557866863 | 1557866864 | 1557866864 | 1557866864 | 1557866864 | date |count| ------------|-----| 2019
recieve_time
1557866863 |
1557866863 |
1557866863 |
1557866863 |
1557866864 |
1557866864 |
1557866864 |
1557866864 |
date |count|
------------|-----|
2019-05-01 |19 |
2019-05-02 |15 |
2019-05-03 |17 |
以下是我的疑问:
SELECT
to_timestamp(recieve_time) as date, count(*)
FROM public.cdrs WHERE
usage_type='0800 Voice Incoming'
and to_timestamp(recieve_time) >='2019-05-01 00:00:00'
AND to_timestamp(recieve_time) <'2019-06-01 00:00:00'
AND main_bzd >0
group by to_timestamp(recieve_time)
我的要求如下:
recieve_time
1557866863 |
1557866863 |
1557866863 |
1557866863 |
1557866864 |
1557866864 |
1557866864 |
1557866864 |
date |count|
------------|-----|
2019-05-01 |19 |
2019-05-02 |15 |
2019-05-03 |17 |
在
选择列表和分组依据
子句中,将结果强制转换为日期
:
CAST(to_timestamp(recieve_time) AS date)
对于格式化日期,应使用函数“to_char”
它支持时间格式化,或者您可以使用提取来分离日期部分
SELECT to_char(to_timestamp( 156049813956389/100000), 'yyyy-mm-dd')
我认为在PostgreSQL中将unix时间戳转换为日期格式的最简单方法如下:
select to_timestamp(1557866863)::date;
to_timestamp
--------------
2019-05-15
(1 row)
因此,完整的SQL应该是:
select
to_timestamp(recieve_time)::date as date,
count(*)
from
public.cdrs
where
usage_type='0800 Voice Incoming'
and receive_time >= extract(epoch from cast('2019-05-01 00:00:00' as timestamptz))
and receive_time < extract(epoch from cast('2019-06-01 00:00:00' as timestamptz))
and main_bzd >0
group by
to_timestamp(recieve_time)::date
选择
to_时间戳(接收时间)::日期为日期,
计数(*)
从…起
public.cdrs
哪里
用法\u type='0800语音输入'
并接收时间>=摘录(从演员阵容中选取历元('2019-05-01 00:00:00'作为时间戳))
接收时间<提取时间(从演员阵容中的历元('2019-06-01 00:00:00'作为时间戳))
和主_bzd>0
分组
发送时间戳(接收时间)::日期
注意:如果在您的receive\u time
列上创建了index
,最好不要在receive\u time
上的函数位于where
子句时使用它来过滤行,这将导致在执行SQL时无法使用index,我的SQL中的上述方法是更好的方法。祝你好运 Postgres中没有这样的unixtimestamp
。在发布之前,请始终彻底搜索堆栈溢出。不要存储整数而不是日期。使用正确的类型。SQL、语言和所有数据库都有日期类型。您存储的整数可能被称为“unix时间戳”,但我们不知道它是否表示秒或毫秒,更不用说历元了。抱歉,我正在从我的表中发布列数据。更糟糕的是,您要执行的查询必须扫描整个表,而不必使用索引,因为to_timestamp(recieve_time)>='2019-05-01 00:00:00'
作用于函数的输出,而不是索引值本身。要使此查询快速运行,必须将日期值转换为integers@BaljotSingh我在上面的回答中给出了一些建议,希望对您有所帮助D