tom
tom

Reputation: 85

Convert time interval into decimal hours in SQL Server

I have a time interval in the format '88:52:57' I need to convert it into a decimal hours in the format 88.88

How can I do this?

I have the data initially loaded as a varchar

Upvotes: 2

Views: 1761

Answers (3)

t-clausen.dk
t-clausen.dk

Reputation: 44316

Try this, solution is based on conversions, making it safe, if the format is always (h)h:mi:ss:

DECLARE @S varchar(8) = '88:52:57';
SELECT
  CAST(REPLACE(left(@S, 2), ':', '') as int)+
  CAST(CAST(CAST('0:'+RIGHT(@S, 5) as datetime) as decimal(10,10)) * 24 as decimal(2,2))

Result:

88.88

Upvotes: 1

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

You can use left, right and substring to extract the values and then do some calculations.

declare @S varchar(8) = '88:52:57';

select left(@S, 2) + substring(@S, 4, 2)/60.0 + right(@S, 2)/60.0/60.0;

If you not always have two digit values you can use parsename to get the values instead.

declare @S varchar(20) = '088:052:057';

select parsename(S.X, 3) + parsename(S.X, 2)/60.0 + parsename(S.X, 1)/60.0/60.0
from (select replace(@S, ':', '.')) as S(X)

Upvotes: 4

Gottfried Lesigang
Gottfried Lesigang

Reputation: 67291

Try it like this (best create an UDF from this):

First I split the Time-Variable on its double dots via XML. The rest is simple calculation...

DECLARE @YourTime VARCHAR(100)='88:52:57';

WITH Splitted AS
(
    SELECT CAST('<x>' + REPLACE(@YourTime,':','</x><x>') + '</x>' AS XML) TimeParts
)
,TimeFract AS
(
    SELECT TimeParts.value('/x[1]','float') AS HourPart
           ,CAST(TimeParts.value('/x[2]','int') * 60 + TimeParts.value('/x[3]','int') AS FLOAT) Seconds
    FROM Splitted
)
SELECT HourPart + Seconds/3600   
FROM TimeFract

The result

88,8825

Upvotes: 1

Related Questions