SQL convert time to milliseconds - sql

I have this time-duration: 00:00:23.323
I want to convert it in sql to milliseconds.
EDIT://
I tried this but it isn't very nice:
SELECT (DATEPART(hh,'12:13:14.123') * 60 * 60 * 1000)
SELECT (DATEPART(n,'12:13:14.123') * 60 * 1000)
SELECT (DATEPART(s,'12:13:14.123') * 1000)
SELECT DATEPART(ms,'12:13:14.123')
How does it work?
Thanks for your answers.

Use DATEDIFF:
SELECT DATEDIFF(MILLISECOND, 0, '00:00:23.323')
Result:
23323

You can use datepart function.
like this
select DATEPART(MILLISECOND,GETDATE())+DATEPART(second,getdate())*1000

I got it, it isn't the nice way but it works:
SELECT (DATEPART(hh,'00:00:23.323') * 60 * 60 * 1000) + (DATEPART(n,'00:00:23.323') * 60 * 1000) + (DATEPART(s,'00:00:23.323') * 1000) + DATEPART(ms,'00:00:23.323') AS 'DurationInMillis'

Related

Left-filling a text field with zeros

I have a postgres database that I can access with PGAdmin III. I run a script to change a number stored in a text field and then add left zeros to file it to four characters. It's a time field that must be stored as text. I'd like to do it in a single run instead of two. Here's the first clause to add hours to the time field as text;
UPDATE timetable
SET eta = (
CASE
WHEN (trips.starttime::int / 100) + (destination.zuluoffset * -1 ) < 24 THEN ((trips.starttime::int / 100) + (destination.zuluoffset * -1 )) * 100
WHEN (trips.starttime::int / 100) + (destination.zuluoffset * -1 ) > 23 THEN ((trips.starttime::int / 100) + (destination.zuluoffset * -1 ) - 24) * 100
END )
FROM
destination,
trips
WHERE
timetable.tripsid = trips.id;
This does fine and adds the desired number of hours while correcting for results of greater than 24 hours. However, this leave any times less than 1000 hours as three digits or even a single 0 for midnight. The field needs to be 4 characters.
So I run this as a second clause;
UPDATE timetable
SET eta = lpad(eta, 4, '0');
and this works also. But how can I add the lpad to the first Update clause? I tried putting the entire CASE statement in the lpad statement in place of eta like this;
SET eta = lpad((CASE statement here), 4, '0')
but I get this error;
ERROR: function lpad(numeric, integer, unknown) does not exist
LINE 3: SET eta = lpad((
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
I've tried casting eta with ::int, ::text, and ::varchar, but that just return a sytax error.
should be LPAD(your_col::text, 4, '0')
UPDATE timetable
SET eta = LPAD ((
CASE
WHEN (trips.starttime::int / 100) + (destination.zuluoffset * -1 ) < 24 THEN ((trips.starttime::int / 100) + (destination.zuluoffset * -1 )) * 100
WHEN (trips.starttime::int / 100) + (destination.zuluoffset * -1 ) > 23 THEN ((trips.starttime::int / 100) + (destination.zuluoffset * -1 ) - 24) * 100
END )::text, 4,'0')
FROM destination
INNER JOIN trips ON timetable.tripsid = trips.id;
Why are you using LPAD if the result of your CASE statement is numeric , use simply to_char :
UPDATE timetable
SET eta = to_char (
CASE
WHEN (trips.starttime::int / 100) + (destination.zuluoffset * -1 ) < 24 THEN ((trips.starttime::int / 100) + (destination.zuluoffset * -1 )) * 100
WHEN (trips.starttime::int / 100) + (destination.zuluoffset * -1 ) > 23 THEN ((trips.starttime::int / 100) + (destination.zuluoffset * -1 ) - 24) * 100
END , 'FM0000')
FROM destination
INNER JOIN trips ON timetable.tripsid = trips.id;

How can i solve that Calculation in SQL

I have a calculation in which i get result but some issue in after Decimal
Place which is:
(31,250x.04) / ((1 + .04)^16.5)-1 = 1,373.52 (this is the original answer)
But when i calculate i get 1,373.626373. So can any one help me to solve it
My Calculation is this:
select (31250 * .04) = 1250.00
select POWER((1.04),16.5)-1 = 0.91
select 1250.00/0.91
You need to cast to better-than-default precision for number literals to get all the digits of the 0.91007... term:
select convert(decimal(18,9), 31250 * 0.04) / (convert(decimal(18,9), power(convert(decimal(18,9), 1 + 0.04), 16.5))-1)
Compare all results using
select convert(real, 31250 * 0.04) / (convert(real, power(1 + 0.04, 16.5))-1)
select convert(float, 31250 * 0.04) / (convert(float, power(1 + 0.04, 16.5))-1)
select convert(decimal(18,9), 31250 * 0.04) / (convert(decimal(18,9), power(convert(decimal(18,9), 1 + 0.04), 16.5))-1)

SQL Convert Milliseconds to Days, Hours, Minutes

I need convert a millisecond value, 85605304.3587 to a value like 0d 18h 21m.
No idea on how to start that, is there something similar to a TimeSpan in SQL like there is in C#?
You can do the calculation explicitly. I think it is:
select floor(msvalue / (1000 * 60 * 60 * 24)) as days,
floor(msvalue / (1000 * 60 * 60)) % 24 as hours,
floor(msvalue / (1000 * 60)) % 60 as minutes
Note: Some databases use mod instead of %.
In MS SQL SERVER you can use next code:
with cte as (
select cast(85605304.3587 as int) / 1000 / 60 as [min]
), cte2 as (
select
cast([min] % 60 as varchar(max)) as minutes,
cast(([min] / 60) % 24 as varchar(max)) as hours,
cast([min] / (60 * 24) as varchar(max)) as days
from cte
)
select concat(days, 'd ', hours, 'h ', minutes, 'm') as tm
from cte2
Using native date & time functions, maybe:
SELECT
AsDateTime = DATEADD(MILLISECOND, 85605304, 0)
, AsDateTime2 = DATEADD(NANOSECOND, 7 * 100, DATEADD(MICROSECOND, 358, DATEADD(MILLISECOND, 85605304, CONVERT(datetime2, CONVERT(datetime, 0)))))
-- Incorrect datetime2 approach I initially did, has some precision loss, probably due to datetime's millisecond issue with 0's, 3's, and 7.'s
--SELECT DontDoThis = DATEADD(NANOSECOND, 7 * 100, DATEADD(MICROSECOND, 358, CONVERT(datetime2, DATEADD(MILLISECOND, 85605304, 0))))
datetime covers only 3 digits beyond seconds, while datetime2 will maintain 7 digits. Perhaps other ways that give date-like objects exist, I wouldn't know.

Is there any way I can convert VARCHAR2 to SECONDS?

My output is like this
**Column1** **Column2**
20170123012057.555 20170123070616.314
I should get 20719 seconds if I minus the two columns
You can convert the values to a date and then take the difference:
select (to_date(substr(column2, 1, 14), 'YYYYMMDDHH24MISS') -
to_date(substr(column1, 1, 14), 'YYYYMMDDHH24MISS')
) * 24 * 60 * 60
Try this. Here I have given difference in milliseconds as well as in seconds which is rounded
select
extract(day from (to_timestamp(column2,'YYYYMMDDHH24MISS.FF')
-to_timestamp(column1,'YYYYMMDDHH24MISS.FF')
)*86400*1000) / 1000
as diff_in_milliseconds
,round(extract(day from (to_timestamp(column2,'YYYYMMDDHH24MISS.FF')-
to_timestamp(column1,'YYYYMMDDHH24MISS.FF')
)*86400*1000) / 1000
) as diff_in_seconds
from
(select
'20170123012057.555' as Column1,
'20170123070616.314' as Column2
from dual)
Output
DIFF_IN_MILLISECONDS DIFF_IN_SECONDS
20718,7590 20719
Try as
SELECT ROUND (seconds / 1000) seconds
FROM (SELECT EXTRACT (DAY FROM cal_col) * 24 * 60 * 60 * 1000
+ EXTRACT (HOUR FROM cal_col) * 60 * 60 * 1000
+ EXTRACT (MINUTE FROM cal_col) * 60 * 1000
+ ROUND (EXTRACT (SECOND FROM cal_col) * 1000)
seconds
FROM (SELECT TO_TIMESTAMP ('20170123070616.314',
'YYYYMMDDHH24MISS.FF')
- TO_TIMESTAMP ('20170123012057.555',
'YYYYMMDDHH24MISS.FF')
cal_col
FROM DUAL))

How to convert hh:mm:ss to seconds in SQL Server with more than 24 hours

I have table name tblAttend in which one column named WorkHrs is of datatype varchar.
The result of simple select query is
I sum this column's value and get result in seconds my query is
select sum(DATEDIFF(SECOND, '0:00:00', WorkHrs ))
from tblAttend
and it shows this output:
Now the issue is, when sum of WorkHrs is greater than 24 hours it will throw an error:
What can you suggest to get around this problem? Thanks in advance
Try splitting each time into its component parts by converting the time to a string and then multiplying by the number of seconds relevant to each part.
Data conversion to integer is implicit
select Sum(Left(WorkHrs,2) * 3600 + substring(WorkHrs, 4,2) * 60 + substring(WorkHrs, 7,2))
from tblAttend
Try:
DECLARE #DURATION TIME = '01:43:24'
SELECT DATEDIFF(SECOND, '1/1/1900', CONVERT(DATETIME, #DURATION))
Try this:
SELECT DATEDIFF(SECOND, CONVERT(DATE,GETDATE()), GETDATE())
I have implemented the following function to use it in the management of my projects :
/****** Object: UserDefinedFunction [dbo].[Seconds] Script Date: 10/6/2017 12:00:22 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
select [dbo].[Seconds]('24:00:00'),(24*3600)
select [dbo].[Seconds]('102:56:08'),(102*3600+56*60+8)
*/
ALTER FUNCTION [dbo].[Seconds] (#Time as varchar(50))
RETURNS int
BEGIN
declare #S int, #H int
set #H=cast(SUBSTRING(#Time,1,CHARINDEX(':',#Time)-1) as int)
IF #H<24
set #S=DATEDIFF(SECOND, '0:00:00', #Time)
ELSE BEGIN
set #H=#H-23
set #Time = '23'+SUBSTRING(#Time,CHARINDEX(':',#Time),LEN(#Time)-2)
set #S = (#H*3600)+DATEDIFF(SECOND, '0:00:00', #Time)
END
RETURN #S
END
You may try like this:
SELECT Sec=SUM((DATEPART(HOUR,column name)*3600)+(DATEPART(MINUTE,column name)*60)+(DATEPART(Second,column name)))
FROM [TableName]
You need to convert your WorkHrs to DATETIME first, then perform the DATEDIFF:
WITH Cte(WorkHrs) AS(
SELECT CAST('02:29:11' AS VARCHAR(10)) UNION ALL
SELECT CAST('21:00:00' AS VARCHAR(10)) UNION ALL
SELECT CAST('25:20:02' AS VARCHAR(10))
),
CteConvert(dt) AS(
SELECT
DATEADD(
SECOND,
CAST(SUBSTRING(WorkHrs, 7, 2) AS INT),
DATEADD(
MINUTE,
CAST(SUBSTRING(WorkHrs, 4, 2) AS INT),
DATEADD(
HOUR,
CAST(SUBSTRING(WorkHrs,1, 2) AS INT),
0
)
)
)
FROM Cte
)
SELECT
SUM(DATEDIFF(SECOND, 0, dt)),
-- Formatted to hh:mm:sss
RIGHT('0' + RTRIM(CONVERT(CHAR(2), SUM(DATEDIFF(SECOND, 0, dt)) / (60 * 60))), 2) + ':' +
RIGHT('0' + RTRIM(CONVERT(CHAR(2), (SUM(DATEDIFF(SECOND, 0, dt)) / 60) % 60)), 2) + ':' +
RIGHT('0' + RTRIM(CONVERT(CHAR(2), SUM(DATEDIFF(SECOND, 0, dt)) % 60)),2)
FROM CteConvert
;with cte as (
select
total =Sum(Left(WorkHrs,2) * 3600 + substring(WorkHrs, 4,2) * 60 + substring(WorkHrs, 7,2))
from tblAttend
)
select
total [Total Time in Seconds],
(total / 3600) [Total Time Hour Part],
((total % 3600) / 60) [Total Time Minute Part],
(total % 60) [Total Time Second Part]
from cte
I think you can isolate each part of the time (hour, minute and second) and than sum what you need, please take a look:
declare #tbl table(WorkHrs VARCHAR(8))
insert into #tbl(WorkHrs) values ('02:29:11')
insert into #tbl(WorkHrs) values ('25:00:11')
-- Sum in minutes
SELECT TRY_CAST(([HOURS] * 60) + [MINUTES] + ([SECOND] / 60) AS INT) as TotalInMinutes
FROM (
SELECT
-- Use this aproach to get separated values
SUBSTRING(WorkHrs,1,CHARINDEX(':',WorkHrs)-1) AS [HOURS],
SUBSTRING(WorkHrs,4,CHARINDEX(':',WorkHrs)-1) AS [MINUTES],
SUBSTRING(WorkHrs,7,CHARINDEX(':',WorkHrs)-1) AS [SECOND] -- probably you can ignore this one
FROM #tbl
)
tbl
-- Or try to sum in seconds
SELECT TRY_CAST(([HOURS] * 3600) + ([MINUTES] * 60) + [SECOND] AS INT) as TotalInSeconds
FROM (
SELECT
-- Use this aproach to get separated values
SUBSTRING(WorkHrs,1,CHARINDEX(':',WorkHrs)-1) AS [HOURS],
SUBSTRING(WorkHrs,4,CHARINDEX(':',WorkHrs)-1) AS [MINUTES],
SUBSTRING(WorkHrs,7,CHARINDEX(':',WorkHrs)-1) AS [SECOND]
FROM #tbl
)
tbl
It will return like this to you:
I hope it can help
You can simply use the TIME_TO_SEC function:
SELECT TIME_TO_SEC(WorkHrs) FROM tblAttend;