removing milliseconds from a oracle tmstmp field

一个人想着一个人 提交于 2019-12-18 08:14:09

问题


I have a TIMESTAMP(6) field in Oracle and I need to remove the millisecond component from the time.

For example I have

10/20/2014 10:34:06.356000 AM

and I would like to remove the milliseconds so that I have

10/20/2014 10:34:06 AM

Do you know the best way to do this?

Thank you!


回答1:


How about this?

select cast(col as timestamp(0))

EDIT:

The easiest way to avoid rounding is to use trunc() or to subtract half a second:

select cast(col - 0.5/(24*60*60) as timestamp(0))



回答2:


try this

SELECT TO_CHAR(SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "NOW"
FROM DUAL;

if you need 12-hour date format

SELECT TO_CHAR(SYSDATE, 'MM-DD-YYYY HH:MI:SS AM') "NOW"
FROM DUAL;

SQL FIDDLE




回答3:


You can either cast it to a timestamp with no fractional seconds (this will round to the nearest second):

CAST( your_timestamp AS TIMESTAMP(0) )

Or to a DATE data type (this will truncate to the nearest second):

CAST( your_timestamp AS DATE )

If you want it as a TIMESTAMP(0) data type then cast it back:

CAST( CAST( your_timestamp AS DATE ) AS TIMESTAMP(0) )

Or you can convert it to a formatted string and specify the format model you want to use (this will truncate to the nearest second):

TO_CHAR( your_timestamp, 'YYYY-MM-DD HH24:MI:SS' )

Like this:

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE your_table ( your_timestamp ) AS
  SELECT TIMESTAMP '2017-10-25 12:53:12.10076' FROM DUAL;

Query 1:

SELECT CAST( your_timestamp AS TIMESTAMP(0) ) AS "Timestamp",
       CAST( your_timestamp AS DATE ) AS "Date",
       TO_CHAR( your_timestamp, 'DD-MM-YYYY HH24:MI:SS' ) AS "String"
FROM   your_table

Results:

|             Timestamp |                 Date |              String |
|-----------------------|----------------------|---------------------|
| 2017-10-25 12:53:12.0 | 2017-10-25T12:53:12Z | 25-10-2017 12:53:12 |

note: How the TIMESTAMP and DATE are formatted in the output will depend on your NLS_TIMESTAMP_FORMAT and NLS_DATE_FORMAT session parameters but you can directly control the formatting of TO_CHAR when you specify a format model.




回答4:


This might help!

select substr(to_char('10/20/2014 10:34:06.356000 AM'),1,instr(to_char('10/20/2014 10:34:06.356000 AM'),'.')-1)||' '||
substr(to_char('10/20/2014 10:34:06.356000 AM'),-2,instr(to_char('10/20/2014 10:34:06.356000 AM'),'.')-1) "Date"
from dual;


来源:https://stackoverflow.com/questions/27659042/removing-milliseconds-from-a-oracle-tmstmp-field

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