Convert time in SQL to 12 hour format WITH seconds on - sql

I have a script that I am using to populate a time dimension table and I would like to have a column for the time in 12 hour format.
I know this can be done by doing something along the lines of
SELECT CONVERT(varchar(15),[FullTime],100)
Where [FullTime] is a column containing a TIME field in HH:MM:SS format.
But this gives the following result 2:30pm and I would like 2:30:47PM, note the inclusion of seconds.
I know I could build this up using substrings etc. but I wondered if there was a prettier way of doing it.
Thanks

SELECT GETDATE() 'Today',
CONVERT(VARCHAR(8), [FullTime], 108) 'hh:mi:ss'
Taken from here
This will give you a column 'today' followed by the time value you seek 'hh:mi:ss'

If having also milliseconds is not a problem for you, you can use
SELECT CONVERT(VARCHAR, [FullTime], 109)

Declare #tstTime datetime
set #tstTime = GetDate()
Select
#tstTime
,CONCAT(SUBSTRING(CONVERT(varchar(26), #tstTime, 109),1,20),RIGHT(CONVERT(varchar(26), #tstTime, 109),2))

Related

SQL Round Seconds on Column to 00 seconds [duplicate]

I'm having a bit of trouble with truncating data. I'm using SQL's GETDATE() function to get the current date and time and enter them into a database. However, I only want to save the date and time up until the minute. In other words, I want dd/mm/yyyy hh:mm:00.000 or dd/mm/yyyy hh:mm to be saved when I input new data. How can I go about doing this?
I should note I'm using MS-SQL.
There are a number of ways to go about doing this.
For example, you could convert the generated datetime from GetDate() to a smalldatetime first, à la:
CAST(GetDate() AS smalldatetime)
To be clear, this will round the generated seconds up (or down) to the nearest minute depending up the value of the current second.
EDIT:
Alternatively, you can have SQL Server truncate a datetime for you for a "cleaner" (READ: no rounding, since the value is pre-truncated) conversion to smalldatetime:
CAST(DateAdd(minute, DateDiff(minute, 0, GetDate()), 0) AS smalldatetime)
For truncation:
SELECT SMALLDATETIMEFROMPARTS(
datepart(year ,dt)
,datepart(month ,dt)
,datepart(day ,dt)
,datepart(hour ,dt)
,datepart(minute,dt)
)
FROM (SELECT GETDATE()) t(dt)
One way is to convert it to smalldatetime for the assignment (and back as needed).
smalldatetime always has seconds and beyond set to 00.
SELECT CONVERT(smalldatetime, GETDATE())
As this may round up or down, another way to safely truncate the seconds would be this:
SELECT CONVERT(datetime, CONVERT(nchar(16), GETDATE(), 120), 120)
The conversion code 120 returns the format yyyy-mm-dd hh:mi:ss.
Combine DATEADD and SMALLDATETIME to truncate
CAST(DATEADD(S, -30, dt) AS SMALLDATETIME)
The other option is not sure why you cannot consider the front-end instead of the back-end so don't change the SQL and thus format in the front-end as dd/MM/yyyy HH:mm or whatever format you need if that is doable or appropriate in the context of what you are trying to achieve. For example in an SSRS report you could format the field in question in the report designer or use the Format function. If it is a webpage or Excel I am sure you could also do something similar.

Calculate Time Difference for Date/Time Variable

I have two variables 'triage_date_time' and 'checkin_date_time'. Both are formatted as, for example, 2018-12-31 14:13:00. Showing the year-month-day and hour-minute-second both within one cell.
I wanted to create a variable that calculates the time it takes from check-in to triage.
I attempted to use the following code:
SELECT DISTINCT datediff(minute, 'triage_date_time', 'checkin_date_time') as
checkin_to_triage
However, when running this code I get the following error... "Conversion failed when converting date and/or time from character string".
Any suggestions of how I can write a code that would calculate the minute difference of these two variables.
Thanks!
One problem is obviously the single quotes. Assuming that you are using SQL Server, variables start with #. So:
select datediff(minute, #triage_date_time, #checkin_date_time) as checkin_to_triage
If you are confused and really mean columns in a table, then:
select datediff(minute, triage_date_time, checkin_date_time) as checkin_to_triage
from t;
could it be that your field is a CHARACTER data type ?
cast your char to datetime
SELECT DISTINCT datediff(minute, CAST(triage_date_time AS datetime), CAST(checkin_date_time AS datetime)) as checkin_to_triage
Try with this query
DECLARE #triage_date_time DATETIME = '20181231 14:13:00'
DECLARE #checkin_date_time DATETIME = '20181231 16:13:00'
SELECT DATEDIFF (MINUTE, #triage_date_time, #checkin_date_time) AS 'checkin_to_triage'
Output :
checkin_to_triage
120

Remove the zeros using SQL Server

Hello I am using SQL Server and I have this column :
data
6/19/2019 3:10:12 PM
12/23/2016 5:02:15 AM
I wanted to extract only the time so I used the following query :
select try_parse([data] as time using 'en-US') from Table_1
But the problem is I get as a result this :
15:10:12.0000000
05:02:15.0000000
All is okay except the 0 I mean I would like to get :
15:10:12
05:02:15
Thank you very much for your help !
You can use TIME() with the correct scale to get your desired results.
select Convert(time(0) , Data ) as time from Table_1
time(0) means a scale of 0, which has a precision of 8. This results as HH:MM:SS. Using another scale, like 1, would give you a single digit for the fractional second. You can read up on all of the scales in the MS Docs
Declare #data varchar(28)='12/23/2016 5:02:15 AM'
select Convert(varchar(20),Cast(#data as time),24)
Try this
select CONVERT(varchar(8), data, 108) from Table_1
that only show time (17:00:59) but you can add + between them if you want full format date as dd/MM/yyyy hh:mm:ss
select CONVERT(varchar(10), data, 101) + ' ' + CONVERT(varchar(8), data, 108) from Table_1
They will work if data using DATETIME type
You can extract time using below query
SELECT CONVERT(VARCHAR(8), cast('12/23/2016 5:02:15 AM' as time),108)
The output is- 05:02:15. I can hope this query/answer is self explanatory.

date time stored as varchar in sql how to filter on varchar

I am working on a project in which dates and times ar stored as a varchar e.g. "30-11-2017,7:30" first date in dd-mm-yyy format and then time separated with a comma. I am trying to filter on it but it is not working correctly kindly guide me how to filter data on date.
select *
from timetrack
where startDateAndTime >= '30-11-2017,7:30'
In attached image records have been shown. When I apply above query it shows no records
You can easily convert your date to SQL datatype datetime uisng parse function, for example select parse('30-11-2017,7:30' as datetime using 'it-IT').
So, in your case, you can apply this function in where clause, so you can easily apply comparison between dates:
select *
from timetrack
where parse(startDateAndTime as datetime using 'it-IT') >= '2017-11-30 07:30:00.000'
Your format is apparently italian :) But you have to specify your own date in the format convertable to datetime, as I have done in above example.
NOTE: parse is available starting with SQL Management Studio 2012.
Unless you are using ISO date format (yyyy-MM-dd HH:mm:ss or close) applying ordering (which inequalities like greater than or equal use) will not work: the date order is disconnected from the string ordering.
You'll need to parse the date and times into a real date time type and then compare to that (details of this depend on which RDBMS you are using).
If, you want to just filter out the date then you could use convert() function for SQL Server
select *
from timetrack
where startDateAndTime >= convert(date, left(#date, 10), 103)
Else convert it to datetime as follow
select *
from timetrack
where startDateAndTime >= convert(datetime, left(#date, 10)+' ' +
reverse(left(reverse(#date), charindex(',', reverse(#date))-1)), 103)
You need the date in a datetime column, Otherwise you can't filter with your current varchar format of your date.
Without changing the existing columns, this can be achieved by making a computed column and making it persisted to optimize performance.
ALTER TABLE test add CstartDateTime
as convert(datetime, substring(startDateAndTime, 7,4)+ substring(startDateAndTime, 4,2)
+ left(startDateAndTime, 2) +' '+ right(startDateAndTime, 5), 112) persisted
Note: this require all rows in the column contains a valid date with the current format
Firstly, you need to check what is the data that is entered in the 'startDateAndTime' column,then you can convert that varchar into date format
If the data in 'startDateAndTime' column has data like '30-11-2017,07:30', you would then have to convert it into date:
SELECT to_date('30-11-2017,07:30','dd-mm-yyyy,hh:mm') from dual; --check this
--Your query:
SELECT to_date(startDateAndTime ,'dd-mm-yyyy,hh:mm') from timetrack;

Truncate seconds and milliseconds in SQL

I'm having a bit of trouble with truncating data. I'm using SQL's GETDATE() function to get the current date and time and enter them into a database. However, I only want to save the date and time up until the minute. In other words, I want dd/mm/yyyy hh:mm:00.000 or dd/mm/yyyy hh:mm to be saved when I input new data. How can I go about doing this?
I should note I'm using MS-SQL.
There are a number of ways to go about doing this.
For example, you could convert the generated datetime from GetDate() to a smalldatetime first, à la:
CAST(GetDate() AS smalldatetime)
To be clear, this will round the generated seconds up (or down) to the nearest minute depending up the value of the current second.
EDIT:
Alternatively, you can have SQL Server truncate a datetime for you for a "cleaner" (READ: no rounding, since the value is pre-truncated) conversion to smalldatetime:
CAST(DateAdd(minute, DateDiff(minute, 0, GetDate()), 0) AS smalldatetime)
For truncation:
SELECT SMALLDATETIMEFROMPARTS(
datepart(year ,dt)
,datepart(month ,dt)
,datepart(day ,dt)
,datepart(hour ,dt)
,datepart(minute,dt)
)
FROM (SELECT GETDATE()) t(dt)
One way is to convert it to smalldatetime for the assignment (and back as needed).
smalldatetime always has seconds and beyond set to 00.
SELECT CONVERT(smalldatetime, GETDATE())
As this may round up or down, another way to safely truncate the seconds would be this:
SELECT CONVERT(datetime, CONVERT(nchar(16), GETDATE(), 120), 120)
The conversion code 120 returns the format yyyy-mm-dd hh:mi:ss.
Combine DATEADD and SMALLDATETIME to truncate
CAST(DATEADD(S, -30, dt) AS SMALLDATETIME)
The other option is not sure why you cannot consider the front-end instead of the back-end so don't change the SQL and thus format in the front-end as dd/MM/yyyy HH:mm or whatever format you need if that is doable or appropriate in the context of what you are trying to achieve. For example in an SSRS report you could format the field in question in the report designer or use the Format function. If it is a webpage or Excel I am sure you could also do something similar.