In a data warehouse, I am building I am receiving DateTime data from one of our sources in numeric(17,9) format. Is there a way in SQL Server to convert the numeric to a DateTime and whilst retaining the time information? For example, a date such as 20210928.110424000 should be converted to 2021-09-28 11:04:24:000. I am able to convert this to 2021-09-28 00:00:00.000 but as you can see I am missing the time information.
The most performant way to do this is probably to use DATETIMEFROMPARTS with arithmetic, rather than using string manipulation.
SELECT
DATETIMEFROMPARTS(
CAST(#date AS int) / 10000,
CAST(#date AS int) / 100 % 100,
CAST(#date AS int) % 100,
CAST(#date * 100 AS int) % 100,
CAST(#date % 0.01 * 10000 AS int),
CAST(#date % 0.0001 * 1000000 AS int),
CAST(#date % 0.000001 * 1000000000 AS int)
)
db<>fiddle
A small matter with STUFF(). You only need to be concerned with the time portion... yyyymmdd will convert to a date.
Example
Declare #V numeric(17,9) = 20210928.110424000
Select try_convert(datetime,stuff(stuff(stuff(stuff(#V,16,0,'.'),14,0,':'),12,0,':'),9,1,' '))
Results
2021-09-28 11:04:24.000
Another way to do it, using substring would be:
declare #date numeric(17,9) = 20210928.110424000
-- mask 2021-09-28 11:04:24.000 (121)
select
convert(datetime,
substring(convert(varchar(20),#date),1,4) + '-' +
substring(convert(varchar(20),#date),5,2) + '-' +
substring(convert(varchar(20),#date),7,2) + ' ' +
substring(convert(varchar(20),#date),10,2) + ':' +
substring(convert(varchar(20),#date),12,2) + ':' +
substring(convert(varchar(20),#date),14,2) + '.' +
substring(convert(varchar(20),#date),16,3)
,121)
You can test on this db<>fiddle
Nevertheless, in traditional BI environments, the dates used to be linked to date/time dimensions (with surrogate keys numeric), rather than date/datetime. This strategy allows you to group the data from the dimension, where for a given surrogate key (i.e. YYYYMMDD) you have any other attributes associated (year, quarter, semester, month, week, ...).
Related
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
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'
I am trying to convert a smallint to a time format.
I am using SQL Server 2005 which doesn't support the time datatype.
I am storing the time as 1400 which is a smallint. When retrieving I want it to be converted to a time format. Such as 14:00
Any ideas or guidance on the matter. If there is an easier way to do it or if the way I am trying is possible?
You can get a result as varchar by using this:
SELECT
RIGHT('0' + CONVERT(varchar(10), yourTime / 100), 2) + ':' +
RIGHT('0' + CONVERT(varchar(10), yourTime % 100), 2) As timeString
FROM
yourTable
You can also have a result in DATETIME format like this:
SELECT
CONVERT(datetime, CONVERT(varchar(10), yourTime / 100)+ ':' + CONVERT(varchar(10), yourTime % 100))
FROM
yourTable
In SQL Server 2012+ you can have a result in time format:
SELECT
TIMEFROMPARTS(yourTime / 100, yourTime % 100, 0, 0, 0) As timeFormat
FROM
yourTable
I'm trying to calculate the difference between two datetime values.
I tried datediff(s, begin,end) and datediff(ms, begin,end) however I want the difference to be returned as seconds,milliseconds like the following:
4,14
63,54
SELECT
DATEDIFF(MILLISECOND, begin, end) / 1000,
DATEDIFF(MILLISECOND, begin, end) % 1000
FROM ...;
If you absolutely must form it as a string in your SQL query (can't your presentation tier do that?), then:
SELECT
CONVERT(VARCHAR(12), DATEDIFF(MILLISECOND, begin, end) / 1000)
+ ','
+ RIGHT('000' + CONVERT(VARCHAR(4), DATEDIFF(MILLISECOND, begin, end) % 1000), 3)
FROM ...;
Also I really hope you have better column names than begin and end.
Actually, the marked answer originally produced wrong results for milliseconds 1 - 99:
Example 1 second, 27 milliseconds:
DATEDIFF % 1000 will return 27
CONVERT will convert to '27'
String concatenation will build '1' + ',' + '27'
Result: '1.27' which means 270ms rather than 27ms
Don't forget to pad the milliseconds to three zeros:
DECLARE #start datetime2(7) = '2015-07-03 09:24:33.000'
DECLARE #end datetime2(7) = '2015-07-03 09:24:34.027'
SELECT
CAST (DATEDIFF(SECOND, #start, #end) AS nvarchar(3)) + N'.' +
RIGHT('000' + CAST((DATEDIFF(MILLISECOND, #start, #end) % 1000) AS nvarchar(3)), 3)
DATEDIFF takes only two arguments in MySQL. This works for me:
TIMESTAMPDIFF(SECOND, NOW(), '2019-09-09 18:52:00')
I need to calculate the total length in terms of Hours, Minutes, Seconds, and the average length, given some data with start time and end time.
For example the result must be something like 45:15:10 which means 45 hours 15 min 10 sec, or 30:07 for 30 min 07 sec.
We're using SQL Server 2008 R2 and the conversion failed when time is more than 24:59:59. Any idea of how I could do this?
For information, the columns in the table are Id, StartDateTime, EndDateTime, etc. I need to make a monthly report which contains the recordings count of the month, the total length of these records, and the average length. I'd like to know if there is an easy way to perform all of this.
You shouldn't be converting to time - it is meant to store a point in time on a single 24h clock, not a duration or interval (even one that is constrained on its own to < 24 hours, which clearly your data is not). Instead you can take the datediff in the smallest interval required (in your case, seconds), and then perform some math and string manipulation to present it in the output format you need (it might also be preferable to return the seconds to the application or report tool and have it do this work).
DECLARE #d TABLE
(
id INT IDENTITY(1,1),
StartDateTime DATETIME,
EndDateTime DATETIME
);
INSERT #d(StartDateTime, EndDateTime) VALUES
(DATEADD(DAY, -2, GETDATE()), DATEADD(MINUTE, 15, GETDATE())),
(GETDATE() , DATEADD(MINUTE, 22, GETDATE())),
(DATEADD(DAY, -1, GETDATE()), DATEADD(MINUTE, 5, GETDATE())),
(DATEADD(DAY, -4, GETDATE()), DATEADD(SECOND, 14, GETDATE()));
;WITH x AS (SELECT id, StartDateTime, EndDateTime,
d = DATEDIFF(SECOND, StartDateTime, EndDateTime),
a = AVG(DATEDIFF(SECOND, StartDateTime, EndDateTime)) OVER()
FROM #d
)
SELECT id, StartDateTime, EndDateTime,
[delta_HH:MM:SS] = CONVERT(VARCHAR(5), d/60/60)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), d/60%60), 2)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), d % 60), 2),
[avg_HH:MM:SS] = CONVERT(VARCHAR(5), a/60/60)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), a/60%60), 2)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), a % 60), 2)
FROM x;
Results:
id StartDateTime EndDateTime delta_HH:MM:SS avg_HH:MM:SS
-- ------------------- ------------------- -------------- ------------
1 2013-01-19 14:24:46 2013-01-21 14:39:46 48:15:00 42:10:33
2 2013-01-21 14:24:46 2013-01-21 14:46:46 0:22:00 42:10:33
3 2013-01-20 14:24:46 2013-01-21 14:29:46 24:05:00 42:10:33
4 2013-01-17 14:24:46 2013-01-21 14:25:00 96:00:14 42:10:33
This isn't precisely what you asked for, as it won't show just MM:SS for deltas < 1 hour. You can adjust that with a simple CASE expression:
;WITH x AS (SELECT id, StartDateTime, EndDateTime,
d = DATEDIFF(SECOND, StartDateTime, EndDateTime),
a = AVG(DATEDIFF(SECOND, StartDateTime, EndDateTime)) OVER()
FROM #d
)
SELECT id, StartDateTime, EndDateTime,
[delta_HH:MM:SS] = CASE WHEN d >= 3600 THEN
CONVERT(VARCHAR(5), d/60/60) + ':' ELSE '' END
+ RIGHT('0' + CONVERT(VARCHAR(2), d/60%60), 2)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), d % 60), 2),
[avg_HH:MM:SS] = CASE WHEN a >= 3600 THEN
CONVERT(VARCHAR(5), a/60/60) + ':' ELSE '' END
+ RIGHT('0' + CONVERT(VARCHAR(2), a/60%60), 2)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), a % 60), 2)
FROM x;
This query changes the delta column in the 2nd row in the above result from 0:22:00 to 22:00.
I slightly modified Avinash's answer as it may end with error if difference is too big. If you need only HH:mm:ss it is sufficient to distinguish at seconds level ony like this:
SELECT CONVERT(time,
DATEADD(s,
DATEDIFF(s,
'2018-01-07 09:53:00',
'2018-01-07 11:53:01'),
CAST('1900-01-01 00:00:00.0000000' as datetime2)
)
)
SELECT CONVERT(time,
DATEADD(mcs,
DATEDIFF(mcs,
'2007-05-07 09:53:00.0273335',
'2007-05-07 09:53:01.0376635'),
CAST('1900-01-01 00:00:00.0000000' as datetime2)
)
)
If you want to do averages, then the best approach is to convert to seconds or fractions of a day. Day fractions are convenient in SQL Server, because you can do things like:
select avg(cast(endtime - starttime) as float)
from t
You can convert it back to a datetime using the reverse cast:
select cast(avg(cast(endtime - starttime as float) as datetime)
from t
The arithmetic to get the times in the format you want . . . that is a pain. You might consider including days in the final format, and using:
select right(convert(varchar(255), <val>, 120), 10)
To get the hours exceeding 24, here is another approach:
select cast(floor(cast(<val> as float)*24) as varchar(255))+right(convert(varchar(255), <val>, 120), 6)
It uses convert for minutes and seconds, which should be padded with 0s on the left. It then appends the hours as a separate value.
Starting in SQL SERVER 2012, you don't need to use DATEDIFF function. You can use FORMAT function to achieve what you want:
SELECT
FORMAT(CONVERT(TIME, [appoitment].[Start] - [appointment].[End]), N'hh\:mm') AS 'Duration'
FROM
[tblAppointment] (NOLOCK)
A way that avoids overflows and can include days and go all the way to milliseconds in the output:
DECLARE #startDate AS DATETIME = '2018-06-01 14:20:02.100'
DECLARE #endDate AS DATETIME = '2018-06-02 15:23:09.000'
SELECT CAST(DATEDIFF(day,'1900-01-01', #endDate - #startDate) AS VARCHAR) + 'd ' + CONVERT(varchar(22), #endDate - #startDate, 114)
The above will return
1d 01:03:06:900
And, off course, you can use the formatting of your choice
SQL Supports datetime substraction which outputs a new datetime relative to the MIN date (for instance 1900-01-01, you can probably get this value from some system variable) This works better than DATEDIFF, because DATEDIFF will count ONE for each "datepart boundaries crossed", even if the elapsed time is less than a whole datapart. Another nice thing about this method is that it allows you to use the date formatting conversions.
If days is the (positive) number of days, like 0.5 for 12 hours, use this expression to format it as a proper duration:
CONVERT(varchar(9), FLOOR(days * 24)) + RIGHT(CONVERT(char(19), CAST(days AS datetime), 120), 6)
Excel will understands values up to 9999:59:59 when pasted. There apply a custom format: [h]:mm:ss in the English version ([u]:mm:ss for Dutch).