Two questions for formatting timestamp and number using postgresql

六月ゝ 毕业季﹏ 提交于 2019-12-12 04:16:05

问题


I am selecting a date column which is in the format "YYYY-MM-DD".

I want to cast it to a timestamp such that it will be "YYYY-MM-DD HH:MM:SS:MS"

I attempted:

select CAST(mycolumn as timestamp) from mytable;

but this resulted in the format YYYY-MM-DD HH:MM:SS

I also tried

select TO_TIMESTAMP(mycolumn,YYYY-MM-DD HH:MM:SS:MS) from mytable;

but this did not work either. I cannot seem to figure out the correct way to format this. Note that I only want the first digit of the milliseconds.

//////////////second question

I am also trying to select numeric data such that there will not be any trailing zeros.

For example, if I have values in a table such as 1, 2.00, 3.34, 4.50.

I want to be able to select those values as 1, 2, 3.34, 4.5.

I tried using ::float, but I occasionally strange output. I also tried the rounding function, but how could I use it properly without knowing how many decimal points I need before hand?

thanks for your help!


回答1:


It seems that the functions to_timestamp() and to_char() are unfortunately not perfect. If you cannot find anything better, use these workarounds:

with example_data(d) as (
    values ('2016-02-02')
    )
select d, d::timestamp || '.0' tstamp
from example_data;

     d      |        tstamp         
------------+-----------------------
 2016-02-02 | 2016-02-02 00:00:00.0
(1 row)

create function my_to_char(numeric)
returns text language sql as $$
    select case 
        when strpos($1::text, '.') = 0 then $1::text
        else rtrim($1::text, '.0')
    end
$$;

with example_data(n) as (
    values (100), (2.00), (3.34), (4.50))
select n::text, my_to_char(n)
from example_data;

  n   | my_to_char 
------+------------
 100  | 100
 2.00 | 2
 3.34 | 3.34
 4.50 | 4.5
(4 rows)

See also: How to remove the dot in to_char if the number is an integer




回答2:


SELECT to_char(current_timestamp, 'YYYY-MM-DD HH:MI:SS:MS');

prints

2016-02-05 03:21:18:346



回答3:


just add ::timestamp without time zone

select mycolumn::timestamp without time zone  from mytable;


来源:https://stackoverflow.com/questions/35225868/two-questions-for-formatting-timestamp-and-number-using-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!