Skip to Main Content
  • Questions
  • Subtract hours and show milliseconds for a TIMESTAMP(6) column

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Francisco.

Asked: August 10, 2018 - 4:58 pm UTC

Last updated: August 16, 2018 - 8:06 pm UTC

Version: 10.2.0.4.0 - 64bit

Viewed 10K+ times! This question is

You Asked

I want to SELECT a TIMESTAMP(6) with milliseconds, but at the same time I need to subtract 3 hours (0.125 of a day) from that TIMESTAMP to convert it to my timezone. So I tried:

SELECT To_Char(UTCSCANTIME-0.125,'YYYY-MM-DD HH24:MI:SS') AS LOCALSCANTIME
Outcome: 2018-08-01 19:22:39


If I append "FF" to show milliseconds:

SELECT To_Char(UTCSCANTIME-0.125,'YYYY-MM-DD HH24:MI:SS.FF') AS LOCALSCANTIME
Outcome: ORA-01821: date format not recognized


However if I keep the "FF" but I don't subtract 0.125:

SELECT To_Char(UTCSCANTIME,'YYYY-MM-DD HH24:MI:SS.FF') AS LOCALSCANTIME
Outcome: 2018-08-01 22:22:39.259000


How can I achieve both things?

Thanks in advance!

and we said...


Subtracting a NUMBER value (being a number of days) from a datetime value is an Oracle-specific operation (not in SQL Standard) and it is supported for the DATE data type only. When you attempt this operation on a TIMESTAMP(6) value, the database performs an implicit conversion from TIMESTAMP(6) to DATE. This is why you cannot use a TIMESTAMP-specific format model element FF on the result: DATE does not store fractional seconds. To achieve what you want, use a day-to-seconds interval:

select to_char(UTCSCANTIME - interval '3' hour,'YYYY-MM-DD HH24:MI:SS.FF') as LOCALSCANTIME from ...


Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Another way

A reader, August 20, 2018 - 7:52 pm UTC

You could also do something like

select To_Char(UTCSCANTIME at time zone 'GMT','YYYY-MM-DD HH24:MI:SS') from ...


using the apropriate value for timezone.

More to Explore

SQL

The Oracle documentation contains a complete SQL reference.