Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove milliseconds from Timestamp in Oracle? [duplicate]

I want to export data from 'My_Customer' table in .csv format.
I am extracting a time field but I am getting the output along with Milliseconds.
Eg:
The output I am getting,
25-10-2017 12:53:12:00076
I want to remove/truncate the milliseconds.

Expected Output-
25-10-2017 12:53:12.

I have tried to_char() but it isn't giving proper output. (Instead of giving the exact time available in that field, it is rounding off).

like image 760
Thangaraj Murugananthan Avatar asked Oct 18 '25 16:10

Thangaraj Murugananthan


2 Answers

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 )

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 |

How the TIMESTAMP and DATE are formatted 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.

like image 59
2 revsMT0 Avatar answered Oct 21 '25 07:10

2 revsMT0


Convert your timestamp to a character string:

SQL> SELECT TO_CHAR (SYSTIMESTAMP, 'YYYY-MON-DD HH24:MI:SS') AS my_date
  FROM DUAL;

MY_DATE
-----------------------------
2017-OCT-13 00:38:26
like image 32
Cyrille MODIANO Avatar answered Oct 21 '25 07:10

Cyrille MODIANO