zfxcms ^回到顶部

您的当前位置:首页 > 最新IT资讯 > postgresql > postgresql当前时间

postgresql当前时间

所属分类: postgresql   2019-05-27 11:23:13  编辑:admin  浏览次数 694 次

 Postgresql 当中有四种方式获取当前时间。
 一:now()
     通过now()获取的时间是最完整的时间,包括时区,秒也保留到了6位小数。
     select now();
     得到的结果如下
     '2014-12-24 09:28:31.545145+08'

 二:current_timestamp效果是和now()一样的。

 三:current_time 
      只显示当前的时间,不包括日期
      select current_time;
      得到的结果如下
      '09:32:02.039705+08'

 四:current_date
       只显示当前的日期,不包括小时等信息
       select current_date;
       得到的结果如下
       '2014-12-24'

 我们还可以控制now()的返回格式,如下
  select now()::timestamp(0)without time zone;(current_timestamp 是和now()一样的)
 
 时间的计算方式,如下
 select now() + interval '10 min/year/month/day/hour/sec/ (1 year 1 month 1 day 1 hour 1 min 1 sec)'

--按年分组查看

   select  to_char(time_field, 'YYYY') as d ,  count(id)  as  total_count,sum (count_field)  as  total_amount from  table_name
  where  time_field  between  start_time  and  end_time group by d

--按月分组查看
   select  to_char(time_field, 'YYYY-MM') as d ,  count(id)  as  total_count,sum (count_field)   as  total_amount from  table_name
  where time_field between  start_time  and  end_time  group by d

--按天分组查看
   select  to_char(time_field, 'YYYY-MM-DD') as d ,  count(id)  as  total_count,sum (count_field)   as  total_amount from  table_name
  where time_field between  start_time  and  end_time  group by d


--按小时分组查看
     select  to_char(time_field, 'YYYY-MM-DD  HH24 ' ) as d ,  count(id)  as  total_count,sum (count_field)   as  total_amount from  table_name
  where time_field  between start_time  and  end_time  group by d  order  by  d

--按秒分组查看
     select  to_char(time_field, 'YYYY-MM-DD  HH24:MI:SS ' ) as d ,  count(id)  as  total_countl,sum (count_field)   as  total_amount from  table_name
  where  time_field  between start_time  and  end_time  group by d

一、问题

  使用PostgreSQL获取当前系统时间戳。众所周知,在MySQL中是这样的:

   select UNIX_TIMESTAMP(NOW())

二、解决方案

(1)精确到秒

  select floor(extract(epoch from now())); 结果:"1574826646"

 

(2)精确到秒的小数

  select extract(epoch from now());结果:"1574826646.79929"

 

(3)精确到毫秒:

  select floor(extract(epoch from((current_timestamp - timestamp '1970-01-01 00:00:00')*1000)));


--日期转时间戳

SELECT EXTRACT(epoch FROM NOW()); 

SELECT EXTRACT(epoch FROM CAST('2017-12-06 00:17:10' AS TIMESTAMP)); 

 

--时间戳转日期

SELECT TO_TIMESTAMP(1512490630)


在PostgreSQL中可以直接对时间进行加减运算:、

SELECT now()::timestamp + '1 year';  --当前时间加1年
SELECT now()::timestamp + '1 month';  --当前时间加一个月
SELECT now()::timestamp + '1 day';  --当前时间加一天
SELECT now()::timestamp + '1 hour';  --当前时间加一个小时
SELECT now()::timestamp + '1 min';  --当前时间加一分钟
SELECT now()::timestamp + '1 sec';  --加一秒钟
select now()::timestamp + '1 year 1 month 1 day 1 hour 1 min 1 sec';  --加1年1月1天1时1分1秒
SELECT now()::timestamp + (col || ' day')::interval FROM table --把col字段转换成天 然后相加


随笔文章检索

随笔文章目录