Convert seconds to '00:00:00' format - SQL Server - sql

I have a report in which i have to calculate overall worked hours by any employee in a week. The report reflects hours more than 24 hours(or 86400 seconds). I want to convert all the seconds into "00:00:00" format keeping the format of the columns as datetime or time so that I can do further analysis using the time field.
Below is what I have tried so far:
Declare #WorkTimeInSeconds int
Set #WorkTimeInSeconds = 144000 **--This value is an example. Mostly values are above 86400 seconds**
Select ActualHoursWorked = convert(varchar,(#WorkTimeInSeconds)/3600)
+ ':' + right( '0' + convert(varchar,((#WorkTimeInSeconds) %3600)/60),2)
+ ':' + right( '0' + convert(varchar,(#WorkTimeInSeconds) %60),2)
Above code gives me what I need however the above converts the seconds in INT to varchar which is not what I need for the report. I need the output to be in datetime/time format which can give me results like '40:00:00' for the above example.
I hope I am able I have provided all the information. Please help as I am struggling with this from many days.
Expected Output: 40:00:00

Maybe try CONVERT style 108.
SELECT CONVERT(varchar(10),convert(varchar,(#WorkTimeInSeconds)/3600)
+ ':' + right( '0' + convert(varchar,((#WorkTimeInSeconds) %3600)/60),2)
+ ':' + right( '0' + convert(varchar,(#WorkTimeInSeconds) %60),2),108)

Related

PROGRESS ODBC SQL Covert string into time

i need to convert string into time. I have 2 columns, one of them have date in good format but time looks like this:
Time
_____
061923
060239
134803
135011
first 2 characters are hours, second 2 are minutes and last 2 are seconds. How to convert it into format like "HH:MM:SS" ? Im using progress odbc.
You can insert ':' into the string and convert to a time:
select cast( (left(col, 2) + ':' + substring(col, 3, 2) + ':' + right(col, 2)) as time)

sql convert string to date/datetime

My Filename column looks like 'D181115.T000000'. I used the following code to make it a string, looks like '2018-11-15'.
select '20' + substring(filename, 2,2) + '-' + substring(filename, 4,2) + '-' + substring(filename,6,2)
from table_name
Then I want to convert the string to date type (because I need to sort by date)
select convert(datetime, '20 + substring(filename, 2,2) + '-' + substring(filename, 4,2) + '-' + substring(filename,6,2)')
from table_name
Then I got this error message:
The data types varchar and varchar are incompatible in the subtract
operator.
Any help will be greatly appreciated!
I suspet the database is SQL Server. In that case one can use just
select cast('20' + substring('D181115.T000000', 2,6) as date)
or
select try_cast('20' + substring('D181115.T000000', 2,6) as date)
YYYYMMDD is one of the two unambiguous date formats. The other is the full ISO8601 date+time format. YYYY-MM-DD on the other hand depends on the DATEFORMAT setting
Update
I'd suggest performing this conversion as part of data loading though. Applying functions to a field prevents the server from using any indexes that cover the field. The server will have to scan the entire table in order to produce the final values used for filtering and sorting.
At least consider addd an indexed computed column that produces the file date
I want to convert the string to date type
Look at the first and 2nd statements you included, they are different in that you are missing a quote and you added an extra quote in the second one.
declare #filename varchar(20) = 'D181115.T000000'
select convert(datetime, '20' + substring(#filename, 2,2) + '-' + substring(#filename, 4,2) + '-' + substring(#filename,6,2))
Produces output:
2018-11-15 00:00:00.000

How to properly combine static hour and minute

We have in our table, in SQL Server 2008, the datetime is only holding the date.
There is also an hour col and a minute col, there are for the appointment. the are both columns defined as number.
The hour is typically like this:
12.00
and minute is like 40.00. I tried adding them but it gives a total rather than
12:40 which is what we need. How can I get this to show 12:40. With the : would be better.
Well... taking a shot here, for SQL Server
declare #table table (d datetime,h decimal(4,2), m decimal(4,2))
insert into #table
values
('20170113',12.00,40.00),
('20170113',9.00,8.00)
select
d + cast(left(h,len(floor(h))) + ':' + cast(left(m,len(floor(m))) as varchar(2)) + ':' + '00' as datetime)
from
#table
Prepend 00. to minutes - please note that dot there.
Convert both to times.
Add them.
Convert result back to string.
This way You will also corectly handle situation like 12.40 + 00.30.00 = 13.10

Convert minutes in Numeric format to Hours and minutes format

I Have Minutes as 1064 in a column called 'Efforts_in_minutes' and I need the Output in the format of HH:MM (i.e) 17:44. I have tried the below Query
SELECT Cast(Round(Total_Effort_in_Minutes / 60, 0, 2) AS VARCHAR)
+ ':'
+ Cast(Total_Effort_in_Minutes % 60 AS VARCHAR(2))
FROM PPS
I got the output as 17.000000:44 but What i Need is 17:44
Please advice how to achieve that.
The use of the Round function is unnecessary. Just do integer division:
select CAST(CAST(Total_Effort_in_Minutes AS INT) / 60 AS VARCHAR)
+ ':' + CAST(Total_Effort_in_Minutes % 60 AS VARCHAR(2) )
If your column Total_Effort_in_Minutes already has an integer data type, then you can simplify to:
select CAST(Total_Effort_in_Minutes / 60 AS VARCHAR)
+ ':' + CAST(Total_Effort_in_Minutes % 60 AS VARCHAR(2) )
If you need the minute part to be left-padded with zero to get at least 2 digits, then:
select RIGHT('0' + CAST(CAST(Total_Effort_in_Minutes AS INT) / 60 AS VARCHAR), 2)
+ ':' + CAST(Total_Effort_in_Minutes % 60 AS VARCHAR(2) )
SELECT DATEADD(MI,Total_Effort_in_Minutes,TIMEFROMPARTS(0,0,0,0,0))
FROM PPS
Best practice: The client should decide how to represent the time based on the locale, to allow for variants such as 24H clock vs AM/PM.
Please see this link: https://stackoverflow.com/a/19887500/6298495
Creating an inline function is a good solution provided in the link.
Just for fun:
SELECT CONVERT(CHAR(5), DATEADD(mi, 1064, 0), 8)

SQL Change format of datetime to specific style

I'm trying to convert a datetime value to a specific format, but noe of the style codes seem to do what I want. I tried the SQLUSA post on style codes, but none of them are quite right.
I have a column where the date/time is stored as yyyy-mm-dd hh:nn:ss (24 hour time)
I have a select statement were I want to take this column, but express the date as: mm/dd/yyyy hh:nn:ss AM/PM
The closest I've come is:
CONVERT(varchar,[datetimecolum],22) AS [newcolumnname]
but that only gives me a 2 digit year, not a century year (yyyy).
Any ideas? I'm totally lost. :(
Firstly, datetime fields are not stored in a specific string format, or but as a serial number. So what you see on screen is not what is stored but rather your database tool's default rendering of the date. Secondly why are you doing this in SQL? If you're passing the value to an application, make the conversion there from a native type. Thirdly, I don't think 22 is a valid conversion code in TSQL. Check http://msdn.microsoft.com/en-us/library/ms187928.aspx, for more info.
From: http://msdn.microsoft.com/en-us/library/ms187928.aspx
Judging by all the other formats listed, it would infer just add 100 to the format number to get "with century" (yyyy).
Although according to the documentation (and my tests) there is no format 22 (or 122) - so you'll have to combine two other formats to get exactly what you need:
CONVERT(varchar,[datetimecolum],101) + ' ' + CONVERT(varchar,[datetimecolum],108) AS [newcolumnname]
SQLFiddle demo
I think this does it
select stuff(convert(varchar(20),getdate(),22),7,2,
CAST( DATEPART(yyyy,getdate()) as CHAR(4)))
This is close but no AM PM
select convert(varchar(100),getdate(),22),
+ ' ' + CAST(DATEPART(mm,getdate()) as CHAR(2))
+ '/' + CAST( DATEPART(dd,getdate()) as CHAR(2))
+ '/' + CAST( DATEPART(yyyy,getdate()) as CHAR(4))
+ ' ' + CAST(DATEPART(HH,getdate()) as CHAR(2))
+ ':' + CAST(DATEPART(mi,getdate()) as CHAR(2))
+ ':' + CAST(DATEPART(ss,getdate()) as CHAR(2))
This is a Even clunkier than my original, but it works, except you won't get leading zeros for hours or minutes. You could modify this code to do that as well, but it will get really messy then, so I leave that to you ;-)
In other words, if the date + time is
3/1/2012 10:01:35 PM,
you will instead get:
3/1/2012 10:1:35 PM
Irritating, eh?
Anyway, here you go. Hope this helps.
SELECT dt.ID,
CASE WHEN EXISTS(SELECT DATEPART(HH, mt.TheDate)
FROM MyTable AS mt
WHERE mt.ID = dt.ID
AND (DATEPART(HH, mt.TheDate)) > 12)
THEN
(SELECT
CONVERT(varchar,(MONTH(dt.TheDate))) + '/' +
CONVERT(varchar,(DAY(dt.TheDate))) + '/' +
CONVERT(varchar,(YEAR(dt.TheDate))) + ' ' +
CONVERT(varchar, DATEPART(HH, dt.TheDate)-12) + ':' +
CONVERT(varchar,(DATEPART(mi, dt.TheDate))) + ':' +
CONVERT(varchar,(DATEPART( ss, dt.TheDate))) + ' PM')
ELSE
(SELECT
CONVERT(varchar,(MONTH(dt.TheDate))) + '/' +
CONVERT(varchar,(DAY(dt.TheDate))) + '/' +
CONVERT(varchar,(YEAR(dt.TheDate))) + ' ' +
CONVERT(varchar, DATEPART(HH, dt.TheDate)) + ':' +
CONVERT(varchar,(DATEPART(mi, dt.TheDate))) + ':' +
CONVERT(varchar,(DATEPART( ss, dt.TheDate))) + ' AM') END As FullDate
FROM MyTable AS dt
you need to do it in 2 parts and you need to use stuff to remove millisecond.I will update if find an other way to get rid of millisecond
SELECT CONVERT(VARCHAR(10), GETDATE(), 101)+' '+STUFF(RIGHT(CONVERT(VARCHAR(26), GETDATE(), 109),14),9,4,'')
output : 09/13/2012 11:15:21PM
Edit: incase you want space before AM/PM then use ' ' instead of '' in stuff
SELECT CONVERT(VARCHAR(10), GETDATE(), 101)+' '+STUFF(RIGHT(CONVERT(VARCHAR(26), GETDATE(), 109),14),9,4,' ')
output : 09/13/2012 11:15:59 PM