Convert varchar to datetime in sql which is having millisec - sql

I have a column abc varchar(100) with data like 2011-09-26 16:36:57.810000
I want to convert this column to DATETIME...
But doing a
Convert(DATETIME, abc,120)
is giving this error:
Conversion failed when converting date and/or time from character string.
Can any one please help me convert my varchar format to datetime in SQL Server 2008?
Thanks in advance

You can use style 121 but you can have only 3 digits for milliseconds (i.e yyyy-mm-dd hh:mi:ss.mmm(24h)) format.
declare #abc varchar(100)='2011-09-26 16:36:57.810'
select convert(datetime,#abc,121)
So you can sort it out by limiting the varchar field to 23 characters before converting as:
declare #abc varchar(100)='2011-09-26 16:36:57.810000'
select convert(datetime,convert(varchar(23),#abc),121)
Or use the Left() function to get first 23 characters as:
select convert(datetime,left(#abc,23),121)
Try to avoid storing date as string.

In case you need 6 digits precision use DATETIME2
SELECT CONVERT(DATETIME2, '2016-08-09T08:08:50.358000', 126) as MSSQLDateTime2
SELECT CONVERT(DATETIME, '2016-08-09T08:08:50.358', 126) as MSSQLDateTime

SQL Server only supports 3 decimal places for milliseconds, so the following will work:
Convert(DATETIME, SUBSTRING(abc, 0, 24) ,120)

Based on GBrian's answer, I came up with:
CONVERT(DATETIME, CONVERT(DATETIME2, abc, 126))
I haven't benchmarked how this stacks up against the substring-based solutions.

Assuming we have the following string variables:
DECLARE #d VARCHAR(100) = '2020-04-06T04:35:07.9490051Z' -- 7 digits nanoseconds
DECLARE #d1 VARCHAR(100) = '2020-04-05T15:00:00Z' -- simple: without nanoseconds
I came up to the solution using CAST operator:
SELECT CAST(LEFT(#d,19) + 'Z' AS DATETIME) -- outputs: 2020-04-06 04:35:07.000
SELECT CAST(LEFT(#d1,19) + 'Z' AS DATETIME) -- outputs: 2020-04-05 15:00:00.000

Related

Convert data and time into a numeric number in sql server

I have a data & time format column which I would like to convert to the following format in Microsoft SQL Server: yyyymmddhhmmss00000
So for example if I have 2021-02-04 11:49:50 this will be converted to 2021020411495000000.
Any one knows how to do it please?
You can use the FORMAT function:
SELECT FORMAT(myDate, 'yyyyMMddHHmmss00000')
By converting the date to NVARCHAR once with format 112 and once with format 8 you can extract the numeric date and the time without milliseconds. After removing : from the time you can concat these two strings and convert them to bigint. Following an example:
DECLARE #d DATETIME = GETDATE()
SELECT CAST(CONVERT(NVARCHAR(8), #d, 112) + REPLACE(CONVERT(NVARCHAR(8), #d, 8), ':', '') + '00000' AS BIGINT)

I need to convert this string to datetime in SQL Server

String:
'01/04/2019 01:50:31.230000000'
Expected result:
01/04/2019 01:50:31.230
as a DATETIME.
Query used:
SELECT CONVERT(DATETIME, '01/04/2019 01:50:31.230000000', 113)
Converting that string, which is in the 103 format, would work if it didn't have the last 6 zero's.
So a SUBSTRING or LEFT could be used to keep only 23 characters.
And then convert it to a DATETIME.
But that string, can be converted just fine to a DATETIME2.
Since a DATETIME2 is more accurate.
And a DATETIME2 can be simply casted or converted to a DATETIME.
Note that DATETIME isn't stored with a format in the table.
The way it's displayed is a setting.
However, you can FORMAT a DATETIME back to a string in the specific format you need. (starting with SQL Server 2012)
Example snippet:
select
col as col_input_string,
CAST(CONVERT(datetime2, col, 103) AS datetime) as col_as_datetime,
FORMAT(CONVERT(datetime2, col, 103), 'dd/MM/yyyy HH:mm:ss.fff') as col_as_formatted_string
from (values
('01/04/2019 01:50:31.230000000')
,('31/12/2018 13:33:44.123456789')
) q(col);
Result:
col_input_string col_as_datetime col_as_formatted_string
01/04/2019 01:50:31.230000000 2019-04-01 01:50:31.230 01/04/2019 01:50:31.230
31/12/2018 13:33:44.123456789 2018-12-31 13:33:44.123 31/12/2018 13:33:44.123
The code you want is:
SELECT CONVERT(datetime,LEFT('01/04/2019 01:50:31.230000000',23),103);
You need to use LEFT as datetime is only accurate to 1/300 of a second; thus you need to trim off the accuracy that can't be used.
Try to use
declare #vardate varchar(50) = '01/04/2019 01:50:31.230000000'
declare #date datetime =convert(date, left(#vardate,23), 103)
declare #time time = convert(time, substring(#vardate,12,12), 14)
select DATEADD(DAY, DATEDIFF(DAY, #time, #date), CAST(#time AS DATETIME)) AS Result
if that does not work check different convert formats.

SQL Server: how to change data entry from VARCHAR to DATETIME?

I have below sample data:
03202012 as date but the column datatype is Varchar.
I want to convert it to 2012-03-20 00:00:00.000 as Datetime.
I tried using
CAST(CONVERT(CHAR(10), Column, 101) AS DATETIME)
But I get an error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Complete code snippet to test:
DECLARE #Column VARCHAR(MAX) = '03202012'
SELECT CAST(CONVERT(CHAR(10), #Column, 101) AS DATETIME)
Use yyyyMMdd format, that always works:
DECLARE #myDateString varchar(10) = '03202012';
SELECT cast( substring(#myDateString, 5, 4)+
substring(#myDateString, 1, 2)+
substring(#myDateString, 3, 2) AS datetime);
I found below script help me solved my concern.
SELECT convert(datetime, STUFF(STUFF('31012016',3,0,'-'),6,0,'-'), 105)
Result: 2016-01-31 00:00:00.000
Thanks all for the effort. :D
In MySQL, you can use the STR_TO_DATE function to convert a string to a date. For your example, it would look like this
STR_TO_DATE("03-02-2012", "%m-%d-%Y");
Note that the format part of the string must match the format part of the date.
Edit: Just found out this is for SQL Server, but I assume this will work there as well.

Char to DateTime Conversion

I have one column capturedatetime(Char(30)):
2006-04-25T15:50:59.997000 PM
And I want to convert it and load it at other table column which have is in DateTime. either by T-sql or SSIS which ever way.
I have tried with:
select CONVERT(datetime, '2006-04-25T15:50:59.997000 PM', 126)
But it creates an error:
Conversion failed when converting date and/or time from character string
Late update:
In this column I also have other data that is in a completely different format:
29-JAN-10 08.57.41.000000 PM
(1) STOP storing datetime data in string columns! This is nothing, nothing, nothing but trouble.
(2) Why on earth does your column get data in two different string formats that aren't even valid? Why does the string use 24 hour time and have AM/PM suffix? Why use a regional string format and Y2K disaster like 29-JAN-10?
Here is one way, but it's awfully ugly. I highly recommend you fix the SSIS process to give you valid datetime values in the first place, if not as datetimes, at least as valid ISO strings (yyyy-mm-ddThh:mm:ss.nnn):
DECLARE #x TABLE (d CHAR(30));
INSERT #x SELECT '2006-04-25T15:50:59.997000 PM'
UNION ALL SELECT '29-JAN-10 08.57.41.000000 PM';
SET LANGUAGE ENGLISH; -- this is important, else style 6 may not work
SELECT
CASE WHEN d LIKE '__[0-9]%' THEN
CONVERT(DATETIME, LEFT(d, 23))
WHEN d LIKE '[0-9][0-9]-%' THEN
CONVERT(DATETIME, CONVERT(CHAR(8),
CONVERT(DATETIME,REPLACE(LEFT(d,9),' ','-'),6),112)
+ ' ' + REPLACE(SUBSTRING(d,11,8),'.',':')
+ ' ' + RIGHT(RTRIM(d),2))
END
FROM #x;
The conversion for 126 requires no spaces ... I've got it to work like this:
declare #T varchar(50)
declare #dt datetime
set #T = '2006-04-25T15:50:59.997'
set #dt = convert(datetime,#t,126)
select #T, #dt
select convert(datetime,left('2006-04-25T15:50:59.997000 PM',23))
or
select convert(datetime,left(capturedatetime,23))
If you use cast, you do not even need to supply a format. Code snippet below tested on SQL 2012 Developer version.
declare #var_string varchar(50) = '2006-04-25T15:50:59.997';
declare #var_datetime datetime = cast(#var_string as datetime);
select #var_string as my_string, #var_datetime as my_variable;

Convert INT to DATETIME (SQL)

I am trying to convert a date to datetime but am getting errors. The datatype I'm converting from is (float,null) and I'd like to convert it to DATETIME.
The first line of this code works fine, but I get this error on the second line:
Arithmetic overflow error converting expression to data type datetime.
CAST(CAST( rnwl_efctv_dt AS INT) AS char(8)),
CAST(CAST( rnwl_efctv_dt AS INT) AS DATETIME),
you need to convert to char first because converting to int adds those days to 1900-01-01
select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))
here are some examples
select CONVERT (datetime,5)
1900-01-06 00:00:00.000
select CONVERT (datetime,20100101)
blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit
convert to char first
declare #i int
select #i = 20100101
select CONVERT (datetime,convert(char(8),#i))
Try this:
select CONVERT(datetime, convert(varchar(10), 20120103))
use a where clause on that field to ignore nulls and zero values
update
table
set
BDOS= CONVERT(datetime, convert(char(8), field))
where
isnull(field,0)<>0
A simpler, and possibly faster solution is to use DATEFROMPARTS and a bit of arithmetic.
DECLARE #v bigint = 20220623;
SELECT DATEFROMPARTS(#v / 10000, #v / 100 % 100, #v % 100);
Result
2022-06-23
db<>fiddle
Convert(VARCHAR(10), CAST(CONVERT(char(8), "Replace with you date") as date), 101) "Your alias"