0

I am trying to extract timestamp out of a filename. The filename looks like 'Relabels for 10-19-2019 15-16-24'. I want to extract the timestamp i.e., 15-16-24 out of that filename. Can anyone help me with the SQL query? I tried using substring but substring doesn't work for all filenames.

3
  • 2
    15-16-24 is a time stamp??? Commented Oct 28, 2019 at 21:35
  • 1
    What filenames did you have a problem with? Commented Oct 28, 2019 at 21:39
  • "I tried something with other data and it didn't work, but I won't share the code, the data, or how it failed" doesn't help us help you. Commented Oct 28, 2019 at 21:53

2 Answers 2

2

If 15-16-24 is intended to be 15:16:24 then I understand it as a time. You can extract it by using right():

select right(filename, 8)

You can even convert it to a time:

select try_convert(time, replace(right(filename, 8), '-', ':'))
Sign up to request clarification or add additional context in comments.

Comments

0

You could be very explicit and use DATETIMEFROMPARTS and SUBSTRING.

declare @dt_string varchar(100) = right('Relabels for 10-19-2019 15-16-24', (8+2)+1+(6+2));

select DATETIMEFROMPARTS(
  SUBSTRING(@dt_string,7,4), -- year
  SUBSTRING(@dt_string,1,2), -- month
  SUBSTRING(@dt_string,4,2), -- day
  SUBSTRING(@dt_string,12,2), -- hour
  SUBSTRING(@dt_string,15,2), -- minute
  SUBSTRING(@dt_string,18,2), -- second
  0 -- millisecond
  ) as dt_parsed;
dt_parsed
2019-10-19 15:16:24.000

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.