0

I need to convert a column that contains dates and times in the format 08-JAN-19 09.35.58.173000000 AM to datetime. I've included the code I've tried below - the code commented out is currently not working.

SELECT [last_updated_at]
    , SUBSTRING([last_updated_at], 1, 9)
    , convert(datetime, SUBSTRING([last_updated_at], 1, 9), 103) as Date
    , SUBSTRING([last_updated_at], 11, 18)
    --, convert(datetime, SUBSTRING([last_updated_at], 11, 18), 103) as Time --This fails
    --, convert(datetime, SUBSTRING([last_updated_at], 1, 9), 103) + convert(datetime, SUBSTRING([last_updated_at], 11, 18), 103) as DateTime --final output datetime column
FROM #temp_dates
4
  • Can you change the schema? Commented May 4, 2021 at 13:44
  • I can, but not sure why that would be required? I tried the below solution from @Vlam and it worked! Commented May 4, 2021 at 14:09
  • 1
    Y2K was 21 years ago. Why are we repeating this blunder? Commented May 4, 2021 at 14:19
  • The root cause of the issue is the schema is wrong. If you can change the schema I suggest you do so. Commented May 4, 2021 at 22:04

2 Answers 2

2

The only problem with your data is that you need the time portion of your date to look like this: 2019-01-08 09:35:58.173 instead of 2019-01-08 09.35.58.173 (the dots after the hour and minute need to be colons instead of dots.

--==== Original formatting
DECLARE @date VARCHAR(20) = '08-JAN-19 09.35.58.173000000'

--==== Solution
SELECT CAST(STUFF(STUFF(@date,13,1,':'),16,1,':') AS DATETIME);

Note that this truncates (not rounds) to the nearest millisecond so, 09:35:58.173 becomes 09:35:58.100. If milliseconds are an issue then a bit more finagling will be required.

Sign up to request clarification or add additional context in comments.

Comments

1

Please try the below:

select convert(datetime, substring(replace(replace('08-JAN-19 09.35.58.173000000', '-', ' '), '.', ':'), 1, 18))

Before you can convert a string to datetime, your string must conform to certain patterns as shown in https://learn.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql?view=sql-server-ver15

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.