Convert string to Datetime - sql

I've received a flat file and after parsing and inserting it in a table. I've a column which has dates in a format yyyyMMddhhmmss
Here, yyyy is year, MM is month, dd is day, hh is hours, mm is minute and ss is seconds part
I'm trying to convert this to DateTime type as mentioned below but not working for me
SELECT CAST(StrDate as DateTime) FROM [dbo].[Mytable]
For example:
Column has a value 20150121190941 in Varchar format and it should be converted to DateTime as 2015-01-21 19:09:41.000
I apologize if it's a duplicate one.

You can use select DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )
declare #dt nvarchar(25) = '20150121190941'
select datetimefromparts(left(#dt,4), substring(#dt,5,2), substring(#dt,7,2),substring(#dt,9,2), substring(#dt,11,2), substring(#dt,13,2), '000')

SQL Server readily recognizes YYYYMMDD as a date. So, converting the first 8 characters to a date is easy. Alas, I don't think there is a time representation without colons.
So, here is one rather brutal method:
select (convert(datetime, left(StrDate, 8)) +
convert(time, substring(StrDate, 9, 2 ) + ':' + substring(StrDate, 11, 2 ) + ':' + substring(StrDate, 13, 2 )
)
)

Declare #dt varchar(50)
set #dt=20150121190941
create table tblDateTbl
(
col1 datetime
)
insert into dt (col1)
select SUBSTRING(#dt,1,4) + '-' + SUBSTRING(#dt,5,2) + '-' + SUBSTRING(#dt,7,2)+ ' ' + SUBSTRING(#dt,9,2)+ ':' + SUBSTRING(#dt,11,2)+ ':' + SUBSTRING(#dt,13,2)+ '.000'

Related

Converting a FLOAT into DATE in SQL?

I wanted to know how to properly convert FLOAT value into a DATE?
The data we receive has a value oriented as such: YYYYMM ex. 201911 (today's Year + Month). However, all the values passing under the YYYYMM column signifies the first of the month ex. 201911 = 11/01/2019.
RIGHT([DATE],2) + '/01/' + LEFT([DATE],4) AS [DATE]
When I try converting it, it doesn't put it in a date format because I tried using it in a DATEADD function and it errored on the field I converted.
If your value is YYYYMM, then one simple method is to convert to a string and then a date:
select convert(date, convert(varchar(255), yyyymm) + '01')
Or, use datefromparts():
select datefromparts(floor(yyyymm / 100), yyyymm % 100, 1)
Please check this :
DECLARE #Date AS FLOAT;
SET #Date = 201911;
SELECT CONVERT(VARCHAR, CAST(CAST(LEFT(#Date,4) AS VARCHAR(4)) + '/01' + '/' + CAST(RIGHT(#Date,2) AS VARCHAR(2)) AS DATE) , 103) As CREATEDDATE
Will output 11/01/2019

How can I convert an integer like 3212007 to date 3-21-2007 uisng IBM DB2 SQL?

The dataset I inherited has a DATE column but the values in this column are integers of the form 3212007 which should be 03-21-2007. I can't get it back into date format.
I can convert the integer to a string using CAST(myinteger as varchar(8)) without difficulty. Then I can CAST that as date by CAST(CAST(myinteger as varchar(8)) as date) which gets me a date. The problem is that my integer is formatted as 'mmddyyyy' so for 3212007, I get 3212-01-07.
select TRANSACTION_DATE from MA_NORFOLK fetch first row only;
[returns: 3212007]
select CAST(TRANSACTION_DATE as VARCHAR) from MA_NORFOLK fetch first row only;
[returns: 3212007]
select CAST(CAST(TRANSACTION_DATE as varchar(8)) as date) from MA_NORFOLK fetch first row only;
[returns: 3212-01-07]
Other posts suggest using CONVERT command, but all I get are errors
"DATE" is not valid in the context where it is used..."
Could you please advise me?
Try this:
date(to_date(digits(dec(3212007, 8)), 'MMDDYYYY'))
If you may have one digit for month, there is an alternative:
select
date
(
case when substr(char_dt, 1, 2)='00'
then translate('EFGH-0D-0C', char_dt, 'ABCDEFGH')
else translate('EFGH-AB-CD', char_dt, 'ABCDEFGH')
end
) dt, char_dt
from
(
select digits(dec(i, 8)) char_dt
from table(values 3212007, 312007) t(i)
) t;
DT CHAR_DT
---------- --------
2007-03-21 03212007
2007-01-03 00312007
This works (at least in MS SQL Server):
SELECT CAST(CONCAT( RIGHT(3212007,4),'-',
(3212007 / 1000000), '-', ((3212007 % 1000000) / 10000)) AS date)
The trick is that you don't know if you will have a single digit, or two-digit month, so you have to start with getting just the right 4 characters as the year. Then by using combinations of modulo and integer divide, you can parse out the month and day.
Of course, you will want to substitute your actual date column for the sample data that I used above.
I think this may works well:
create table #temp(
date int
)
insert into #temp (date)
values(3212007),
(12032019)
select
case when len(cast(date as varchar)) = 7
then
'0' + left(cast(date as varchar), 1) + '-' + substring(cast(date as varchar), 2,2) + '-' + right(cast(date as varchar), 4)
else left(cast(date as varchar), 2) + '-' + substring(cast(date as varchar), 3,2) + '-' + right(cast(date as varchar), 4) end
from #temp

SQL conversion from varchar to datetime

One of the columns of my SQL Server table is mm:ss of varchar type where mm = minutes and ss = seconds.
I need to get the average of that column.
Should I convert that column to datetime format first? If so can you tell me how? If not can you tell me what I should do?
Here is my failed attempt to convert it to datetime :
SELECT CONVERT(DATETIME, '2014-01-01 '+Pace+':00', 108)
Where pace is a varchar like 23:05
If you want the average, I would convert the column to number of seconds and work with that:
select avg(pace_secs) as average_in_seconds
from (select cast(left(pace, 2) as int) * 60 + cast(right(pace, 2) as int) as pace_secs
from t
) t;
If you want this back in the format, then you can do:
select right('00' + cast(avg(pace_secs) / 60 as int), 2) + ':' +
right('00' + avg(page_secs) % 60), 2)
from (select cast(left(pace, 2) as int) * 60 + cast(right(pace, 2) as int) as pace_secs
from t
) t;
declare #pace varchar(20) = '23:05 ';
SELECT cast( '2014-01-01 '+cast(#pace as varchar(5))+':00' as datetime)
For SQL2012 and later
SELECT
FORMAT(DATEADD(second,AVG(DATEDIFF(second,0,'00:'+[Pace])),0),'mm:ss')
FROM MyTable

CAST Correct VARCHAR to DateTime

Good Day
I am working of a existing SQL Server Database. What the developers did is to keep the Date and time separate. The Date is in DateTime format (what I want) but the time is incorrect. if it is 14:30 it shows as 1430 when its 09:25 shows as 925. I am trying tyo combine the date and time to have a Date Time view for an program I am writing on top of this database.
I have created the date as a normal date like this:
CASE
WHEN LEN(T0.BeginTime) = 3 THEN '0' + LEFT(T0.BeginTime, 1) + ':' + RIGHT(T0.BeginTime, 2)
ELSE LEFT(T0.BeginTime, 2) + ':' + RIGHT(T0.BeginTime, 2)
END AS 'NEW Start Time'`
The date now looks like it's the correct format but when I want to combine the date and time I get VARCHAR to DateTime error.
How can I fix this?
This is the error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value (ONLY RAN 804 RECORDS)
Thanks
This should do the trick, Hope it helps.
DECLARE #DateTime TABLE (
DateWithTime DATE,
BeginTime INT);
INSERT INTO #DateTime
VALUES ('2014-08-04', '1525'),
('2014-08-04', '525'),
('2014-08-04', '15'),
('2014-08-04', '5'),
('2014-08-04', '0'),
('2014-08-04', '90')
;WITH cte_BeginTimeFix
AS (
SELECT
CONVERT(VARCHAR(10), DateWithTime, 120) AS DateWithTime,
RIGHT('0000' + CAST(BeginTime AS VARCHAR(4)), 4) AS BeginTime
FROM #DateTime
)
, cte_DateString
AS (
SELECT DateWithTime,
BeginTime,
DateWithTime + ' ' + STUFF(STUFF('00:00:00.000', 4, 2, RIGHT(BeginTime, 2)), 1, 2, LEFT(BeginTime, 2)) AS DateTimeStr
FROM cte_BeginTimeFix
)
SELECT DateWithTime,
BeginTime,
CASE
WHEN ISDATE(DateTimeStr) = 1 THEN CAST(DateTimeStr AS DATETIME)
ELSE NULL
END AS DateTimeStr
FROM cte_DateString
A different approach is to convert the time column in minutes and add it to the date
DATEADD(minute, T0.BeginTime / 100 * 60 + T0.BeginTime % 100
, CONVERT(VARCHAR, T0.BeginDate, 112))
with that the length of the time column doesn't matter
This should work:
CONVERT
(
DATETIME,
CONVERT(VARCHAR,T0.Date,112) +
' ' +
CASE
WHEN ISNULL(T0.BeginTime,'0') = '0'
THEN '00:00'
ELSE
RIGHT
(
'00' + LEFT(T0.BeginTime,LEN(T0.BeginTime) - 3),
2
) +
':' +
RIGHT(T0.BeginTime,2)
END
)

combine 2 varchar column's data and convert to datetime

I have 2 columns in a table of varchar datatype.
date and type are the column names in table.
the data present in the table looks like this
date time
20090610 132713
20090610 132734
i need ms sql server query to concatenate these 2 columns data and display as datetime format.
Note :
1. the datatype of those 2 columns cannot be changed now.
2. i tried
select convert(datetime,date + time)
it says "Conversion failed when converting date and/or time from character string."
Suggest the possible solution.
This will return a datetime. The bottom line is to be replaced by your table
select convert(datetime,date,112)+
coalesce(stuff(stuff(rtrim(time), 5,0,':'), 3,0,':'), '') newdate
from
(VALUES ('20090610','132713'),('20090610', '132734'),('20090610', ' ')) yourtable(date,time)
Result:
newdate
2009-06-10 13:27:13.000
2009-06-10 13:27:34.000
2009-06-10 00:00:00.000
You can get it using
SELECT
convert(varchar, convert(datetime, date), 111)
+ ' ' + substring(time, 1, 2)
+ ':' + substring(time, 3, 2)
+ ':' + substring(time, 5, 2)
CREATE TABLE #Table
(
[date] VARCHAR(100),
[time] VARCHAR(100)
)
INSERT INTO #Table VALUES
('20090610','132713'),
('20090610','132734')
;WITH Bits_CTE
AS
(
SELECT
[Date],
[Time],
[hrs] = CONVERT(INT,SUBSTRING([Time], 1, 2)),
[mns] = CONVERT(INT,SUBSTRING([Time], 3, 2)),
[secs] = CONVERT(INT,SUBSTRING([Time], 5, 2))
FROM #Table
)
SELECT
[Date],
[Time],
DATEADD(HOUR,[hrs],
DATEADD(MINUTE,[mns],
DATEADD(SECOND,[secs],[Date])))
FROM Bits_CTE
CREATE FUNCTION [dbo].[DateTimeAdd]
(
#datepart date,
#timepart time
)
RETURNS datetime2
AS
BEGIN
RETURN DATEADD(dd, DATEDIFF(dd, 0, #datepart), CAST(#timepart AS datetime2));
END
Sorry - Missed the bit in your question about storing the date and time as varchars. You would therefore still need to convert these data itemsbefore using this function.