Skip to Main Content
  • Questions
  • Extracting time in HH:MM:SS from a datetime as a string.

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, John.

Asked: May 23, 2017 - 4:23 pm UTC

Last updated: May 25, 2017 - 1:31 am UTC

Version: Oracle Database XE 11.2

Viewed 100K+ times! This question is

You Asked

Hi All,

I'm re-asking this question differently and hopefully someone will be able to help me out

As a quick test I did the following and hopefully it can be replicated

create table t ( test1 varchar2(22) );


The data that I will be working with, the datetime will be entered as per below.

insert into t values ( '05/22/2017 02:20:55 AM' );


When I try now to extract HH:MI:SS using

select to_char(test1, 'hh:mi:ss')
     from t


I get the following error

ORA-01722: invalid number
01722. 00000 - "invalid number"
*Cause: The specified number was invalid.
*Action: Specify a valid number.

Using this test example what can I use to successfully extract the time part only in HH:MM:SS?

In addition
My date format under Database --> NLS is MM/DD/YYYY HH24:MI:SS



with LiveSQL Test Case:

and Connor said...

Since you are storing the date as a string (bad idea) you can use the standard string operations to extract it.

SQL> insert into t values ( '05/22/2017 02:20:55 AM' );

1 row created.

SQL> select substr(test1,12,8) from t;

SUBSTR(TEST1,12,8)
--------------------------------
02:20:55


1 row selected.

Alternatively, you can convert the string to a date, at which point, the to_char functions become available because to_char does *not* take a string as input, but a date or a number (which is why you're getting that error).

SQL> select to_char(to_date(test1,'mm/dd/yyyy hh:mi:ss am'),'hh24:mi:ss') from t;

TO_CHAR(
--------
02:20:55


Ideally, you want the table column to be defined as a DATE, at which point, to_char will work directly on the column.

Rating

  (1 rating)

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

Comments

Learnt something new and it's awesome!

John Barnes, May 25, 2017 - 12:41 am UTC

To be honest I was getting rather frustrated over this "puzzle". I'm taking an Oracle SQL course to gain some understanding of Oracle. As strange as it is I was getting annoyed to the point that I wanted to give on Oracle and stay in my comfort zone with MS SQL Server. I understand and it does make sense to store the date not as a string but unfortunately the source file is in a string and I will have to convert it either way and doing it in a SQL script will be more convenient for me. So this help and information provided was / is very useful and much appreciated.
Connor McDonald
May 25, 2017 - 1:31 am UTC

Glad we could help.

Stick with Oracle ... you'll not regret it :-)