DateDiff to output hours and minutes - sql

my code gives TOTAL HOURS in hours, but i am trying to output something like
TotalHours
8:36
where 8 represents hour part and 36 represents minutes part mean totalHours a person has worked in a single day at office.
with times as (
SELECT t1.EmplID
, t3.EmplName
, min(t1.RecTime) AS InTime
, max(t2.RecTime) AS [TimeOut]
, t1.RecDate AS [DateVisited]
FROM AtdRecord t1
INNER JOIN
AtdRecord t2
ON t1.EmplID = t2.EmplID
AND t1.RecDate = t2.RecDate
AND t1.RecTime < t2.RecTime
inner join
HrEmployee t3
ON t3.EmplID = t1.EmplID
group by
t1.EmplID
, t3.EmplName
, t1.RecDate
)
SELECT EmplID
, EmplName
, InTime
, [TimeOut]
, [DateVisited]
, DATEDIFF(Hour,InTime, [TimeOut]) TotalHours
from times
Order By EmplID, DateVisited

Very simply:
CONVERT(TIME,Date2 - Date1)
For example:
Declare #Date2 DATETIME = '2016-01-01 10:01:10.022'
Declare #Date1 DATETIME = '2016-01-01 10:00:00.000'
Select CONVERT(TIME,#Date2 - #Date1) as ElapsedTime
Yelds:
ElapsedTime
----------------
00:01:10.0233333
(1 row(s) affected)

Try this query
select
*,
Days = datediff(dd,0,DateDif),
Hours = datepart(hour,DateDif),
Minutes = datepart(minute,DateDif),
Seconds = datepart(second,DateDif),
MS = datepart(ms,DateDif)
from
(select
DateDif = EndDate-StartDate,
aa.*
from
( -- Test Data
Select
StartDate = convert(datetime,'20090213 02:44:37.923'),
EndDate = convert(datetime,'20090715 13:24:45.837')) aa
) a
Output
DateDif StartDate EndDate Days Hours Minutes Seconds MS
----------------------- ----------------------- ----------------------- ---- ----- ------- ------- ---
1900-06-02 10:40:07.913 2009-02-13 02:44:37.923 2009-07-15 13:24:45.837 152 10 40 7 913
(1 row(s) affected)

Small change like this can be done
SELECT EmplID
, EmplName
, InTime
, [TimeOut]
, [DateVisited]
, CASE WHEN minpart=0
THEN CAST(hourpart as nvarchar(200))+':00'
ELSE CAST((hourpart-1) as nvarchar(200))+':'+ CAST(minpart as nvarchar(200))END as 'total time'
FROM
(
SELECT EmplID, EmplName, InTime, [TimeOut], [DateVisited],
DATEDIFF(Hour,InTime, [TimeOut]) as hourpart,
DATEDIFF(minute,InTime, [TimeOut])%60 as minpart
from times) source

I would make your final select as:
SELECT EmplID
, EmplName
, InTime
, [TimeOut]
, [DateVisited]
, CONVERT(varchar(3),DATEDIFF(minute,InTime, TimeOut)/60) + ':' +
RIGHT('0' + CONVERT(varchar(2),DATEDIFF(minute,InTime,TimeOut)%60),2)
as TotalHours
from times
Order By EmplID, DateVisited
Any solution trying to use DATEDIFF(hour,... is bound to be complicated (if it's correct) because DATEDIFF counts transitions - DATEDIFF(hour,...09:59',...10:01') will return 1 because of the transition of the hour from 9 to 10. So I'm just using DATEDIFF on minutes.
The above can still be subtly wrong if seconds are involved (it can slightly overcount because its counting minute transitions) so if you need second or millisecond accuracy you need to adjust the DATEDIFF to use those units and then apply suitable division constants (as per the hours one above) to just return hours and minutes.

Just change the
DATEDIFF(Hour,InTime, [TimeOut]) TotalHours
part to
CONCAT((DATEDIFF(Minute,InTime,[TimeOut])/60),':',
(DATEDIFF(Minute,InTime,[TimeOut])%60)) TotalHours
The /60 gives you hours, the %60 gives you the remaining minutes, and CONCAT lets you put a colon between them.
I know it's an old question, but I came across it and thought it might help if someone else comes across it.

Divide the Datediff in MS by the number of ms in a day, cast to Datetime, and then to time:
Declare #D1 datetime = '2015-10-21 14:06:22.780', #D2 datetime = '2015-10-21 14:16:16.893'
Select Convert(time,Convert(Datetime, Datediff(ms,#d1, #d2) / 86400000.0))

If you want 08:30 ( HH:MM) format then try this,
SELECT EmplID
, EmplName
, InTime
, [TimeOut]
, [DateVisited]
, RIGHT('0' + CONVERT(varchar(3),DATEDIFF(minute,InTime, TimeOut)/60),2) + ':' +
RIGHT('0' + CONVERT(varchar(2),DATEDIFF(minute,InTime,TimeOut)%60),2)
as TotalHours from times Order By EmplID, DateVisited

Please put your related value and try this :
declare #x int, #y varchar(200),
#dt1 smalldatetime = '2014-01-21 10:00:00',
#dt2 smalldatetime = getdate()
set #x = datediff (HOUR, #dt1, #dt2)
set #y = #x * 60 - DATEDIFF(minute,#dt1, #dt2)
set #y = cast(#x as varchar(200)) + ':' + #y
Select #y

Difference Two Time in [hh:mm:ss]
select FORMAT((CONVERT(datetime,'2021-12-01 19:24:40') - CONVERT(datetime,'2021-12-01 17:00:00')),'hh:mm:ss')DffTime

this would hep you
DECLARE #DATE1 datetime = '2014-01-22 9:07:58.923'
DECLARE #DATE2 datetime = '2014-01-22 10:20:58.923'
SELECT DATEDIFF(HOUR, #DATE1,#DATE2) ,
DATEDIFF(MINUTE, #DATE1,#DATE2) - (DATEDIFF(HOUR,#DATE1,#DATE2)*60)
SELECT CAST(DATEDIFF(HOUR, #DATE1,#DATE2) AS nvarchar(200)) +
':'+ CAST(DATEDIFF(MINUTE, #DATE1,#DATE2) -
(DATEDIFF(HOUR,#DATE1,#DATE2)*60) AS nvarchar(200))
As TotalHours

Since any DateTime can be cast to a float, and the decimal part of the number represent the time itself:
DECLARE #date DATETIME = GETDATE()
SELECT CAST(CAST(#date AS FLOAT) - FLOOR(CAST(#date AS FLOAT)) AS DATETIME
This will result a datetime like '1900-01-01 hour of the day' you can cast it as time, timestamp or even use convert to get the formatted time.
I guess this works in any version of SQL since cast a datetime to float is compatible since version 2005.
Hope it helps.

In case someone is still searching for a query to display the difference in hr min and sec format:
(This will display the difference in this format: 2 hr 20 min 22 secs)
SELECT
CAST(DATEDIFF(minute, StartDateTime, EndDateTime)/ 60 as nvarchar(20)) + ' hrs ' + CAST(DATEDIFF(second, StartDateTime, EndDateTime)/60 as nvarchar(20)) + ' mins' + CAST(DATEDIFF(second, StartDateTime, EndDateTime)% 60 as nvarchar(20)) + ' secs'
OR can be in the format as in the question:
CAST(DATEDIFF(minute, StartDateTime, EndDateTime)/ 60 as nvarchar(20)) + ':' + CAST(DATEDIFF(second, StartDateTime, EndDateTime)/60 as nvarchar(20))

Sharing a variant that works for more than 24 hours.
DECLARE #sd DATETIME = CONVERT(DATETIME, '12/07/2022 11:10:00', 103)
DECLARE #ed DATETIME = CONVERT(DATETIME, '15/07/2022 13:20:05', 103)
Select Concat (
DATEDIFF(DAY, #sd, #ed), 'd ',
DATEPART(Hour, CONVERT(Time,#ed - #sd)), 'h ',
DATEPART(Minute, CONVERT(Time,#ed - #sd)), 'm ',
DATEPART(Second, CONVERT(Time,#ed - #sd)), 's'
)
Output:
3d 2h 10m 5s

For people that has MySql version < 5.6 as me they don't have TIMESTAMPDIFF so, I wrote MYTSDIFF a function that accepts %s (%m or %i) for minutes %h flags to get the difference in seconds, minutes and hours between 2 timestamps.
Enjoy!
DROP FUNCTION IF EXISTS MYTSDIFF;
DELIMITER $$
CREATE FUNCTION `MYTSDIFF`( date1 timestamp, date2 timestamp, fmt varchar(20))
returns varchar(20) DETERMINISTIC
BEGIN
declare secs smallint(2);
declare mins smallint(2);
declare hours int;
declare total real default 0;
declare str_total varchar(20);
select cast( time_format( timediff(date1, date2), '%s') as signed) into secs;
select cast( time_format( timediff(date1, date2), '%i') as signed) into mins;
select cast( time_format( timediff(date1, date2), '%H') as signed) into hours;
set total = hours * 3600 + mins * 60 + secs;
set fmt = LOWER( fmt);
if fmt = '%m' or fmt = '%i' then
set total = total / 60;
elseif fmt = '%h' then
set total = total / 3600;
else
/* Do nothing, %s is the default: */
set total = total + 0;
end if;
select cast( total as char(20)) into str_total;
return str_total;
END$$
DELIMITER ;

No need to jump through hoops. Subtracting Start from End essentially gives you the timespan
(combining Vignesh Kumar's and Carl Nitzsche's answers) :
SELECT *,
--as a time object
TotalHours = CONVERT(time, EndDate - StartDate),
--as a formatted string
TotalHoursText = CONVERT(varchar(20), EndDate - StartDate, 114)
FROM (
--some test values (across days, but OP only cares about the time, not date)
SELECT
StartDate = CONVERT(datetime,'20090213 02:44:37.923'),
EndDate = CONVERT(datetime,'20090715 13:24:45.837')
) t
Ouput
StartDate EndDate TotalHours TotalHoursText
----------------------- ----------------------- ---------------- --------------------
2009-02-13 02:44:37.923 2009-07-15 13:24:45.837 10:40:07.9130000 10:40:07:913
See the full cast and convert options here:
https://msdn.microsoft.com/en-us/library/ms187928.aspx

Related

How to Find Time difference with hours, minutes and seconds (All Results) in SQL Server

How to Find Time difference with all conditions like
if difference only minutes
49 mintus
if a difference in Hour
1 hour 20 minutes
i am trying
SELECT DATEDIFF(MINUTE,'2018-08-09 10:16:49.000','2018-08-09 11:14:40.000') AS Diff
but this is only show in minutes
I have also tried this one
DECLARE #StartTime datetime = '2018-08-09 10:16:49.000',
#EndTime datetime = '2018-08-09 12:44:05.000'
SELECT CAST(#EndTime - #StartTime as Time) As TimeDiffere
output : 02:27:16.0000000
but I want to 2hr 27mins 16Sec
If your SQL-server version higher than 2012, you can try to sue format function.
CREATE TABLE T(
StartTime datetime,
EndTime datetime
);
insert into t values ('2018-08-09 10:16:49.000','2018-08-09 12:44:05.000')
Query 1:
SELECT format(EndTime - StartTime ,'hh\hr mm\min\s ss\Sec') As TimeDiffere
FROM T
Results:
| TimeDiffere |
|-------------------|
| 02hr 27mins 16Sec |
NOTE
Backslash \ can escape keyword from the format like hr,min,s..., then display it as the original word.
DECLARE #StartTime datetime = '2018-08-09 10:01:15.000',
#EndTime datetime = '2018-08-09 12:50:00.000'
SELECT CONCAT((DATEDIFF(second,#StartTime,#EndTime )/60)/60,'hr ',(DATEDIFF(second,#StartTime,#EndTime)/60)%60,'mins ',DATEDIFF(second,#StartTime,#EndTime)%60,'Sec')
As TimeDiffere
DECLARE #StartTime datetime = '2018-08-09 12:16:49.000',
#EndTime datetime = '2018-08-09 12:44:05.000'
select [hour] + [minute] + [second] as TimeDiffere
from (
select diff_sec = datediff(second, #StartTime, #EndTime)
) t
cross apply
(
select [hour] = isnull(convert(varchar(10), nullif(diff_sec / 60 / 60, 0))
+ ' hours ', '')
) hr
cross apply
(
select [minute] = isnull(convert(varchar(10), nullif(diff_sec / 60 % 60, 0))
+ ' mintues ', '')
) mn
cross apply
(
select [second] = isnull(convert(varchar(10), nullif(diff_sec % 60, 0))
+ ' seconds', '')
) sc
/* RESULT
27 mintues 16 seconds
*/
If you have a poor datetime functionality to get hh.mm.ss, then you can use apply :
select t.*, concat( (dtdiff / 3600), 'hr ', (dtdiff / 60) % 60, 'mins ', dtdiff % 60, 'sec')
from table t cross apply
( values (datediff(second, startdate, enddate))
) tt(dtdiff);

SQL View Query need time interval calculation between 2 dates

I have below View Query. While calculating time interval it only display time interval if check Out is for same date. For example if i check in on 11/12/2017 then it i have to check out with same date 11/12/201 n order to calculate time Interval.
But i want to modify it like if i checkout on next day (after 12:00 AM midnight) it should also calculate the time interval.can some help me to modify query to get the desired results?
Query:
ALTER VIEW [dbo].[TimeAttendanceQuery]
AS
SELECT TOP (100) PERCENT
dbo.AxPerson.Name,
dbo.AxPerson.IdNumber AS EmployeeID,
dbo.TimeAttendance.Badge,
dbo.AxPerson.Id,
MIN(dbo.TimeAttendance.EventTime) AS EntryTime,
MAX(dbo.TimeAttendance.EventTime) AS ExitTime,
CAST(DATEDIFF(second, MIN(dbo.TimeAttendance.EventTime), MAX(dbo.TimeAttendance.EventTime)) / 60 / 60 / 24 AS NVARCHAR(50)) +
':' + CAST(DATEDIFF(second, MIN(dbo.TimeAttendance.EventTime), MAX(dbo.TimeAttendance.EventTime)) / 60 / 60 % 24 AS NVARCHAR(50)) + ':' + CAST(DATEDIFF(second, MIN(dbo.TimeAttendance.EventTime), MAX(dbo.TimeAttendance.EventTime)) / 60 % 60 AS NVARCHAR(50))
AS TimeInterval,
dbo.TimeAttendance.Event,
dbo.AxPerson.Type AS ShitType,
dbo.AxPerson.ShiftDesc,
CONVERT(Varchar,dbo.TimeAttendance.EventTime, 101) AS EventTIME
FROM
dbo.AxPerson
INNER JOIN dbo.TimeAttendance ON dbo.AxPerson.Name = dbo.TimeAttendance.Name
GROUP BY dbo.AxPerson.Name, dbo.AxPerson.IdNumber, dbo.TimeAttendance.Badge, CONVERT(Varchar, dbo.TimeAttendance.EventTime, 101), dbo. AxPerson.ShiftDesc, dbo.AxPerson.Id, dbo.TimeAttendance.Event,dbo.AxPerson.Type
ORDER BY dbo.AxPerson.Name, EventTime DESC
GO
I'm not sure about the algorithm you posted, but if you want to get the time difference from two datetimes you can cast the subtraction as time. This works for less than 24 hours. If you also want the number of days (I think this is only good for less than a year), then you can do the datepart-day of the difference.
For example:
DECLARE #starttime datetime = '2017-11-12 010:20:00'
DECLARE #endtime datetime = '2017-11-13 08:00:00'
SELECT DATEPART(DAY, #endtime - #starttime) - 1 [Days Passed]
,CAST(#endtime - #starttime as time(0)) [Time Passed]
--WHERE the (0) in time(0) is for the milliseconds to return.
Gives output:
Days Passed Time Passed
0 21:40:00
If you don't care about the days, then your code could be modified like this:
ALTER VIEW [dbo].[TimeAttendanceQuery]
AS
SELECT Name, EmployeeID, Badge, Id, EntryTime,
CAST(ExitTime - EntryTime as time(0)) [TimeInterval],
Event, ShiftType, ShiftDesc
,CONVERT(Varchar, EventTime, 101) AS EventTIME
FROM (
SELECT
dbo.AxPerson.Name,
dbo.AxPerson.IdNumber AS EmployeeID,
dbo.TimeAttendance.Badge,
dbo.AxPerson.Id,
MIN(dbo.TimeAttendance.EventTime) AS EntryTime,
MAX(dbo.TimeAttendance.EventTime) AS ExitTime,
dbo.TimeAttendance.Event,
dbo.AxPerson.Type AS ShiftType,
dbo.AxPerson.ShiftDesc,
dbo.TimeAttendance.EventTime
FROM dbo.AxPerson INNER JOIN dbo.TimeAttendance
ON dbo.AxPerson.Name = dbo.TimeAttendance.Name
GROUP BY
dbo.AxPerson.Name,
dbo.AxPerson.IdNumber,
dbo.TimeAttendance.Badge,
dbo.AxPerson.Id,
dbo.TimeAttendance.Event,
dbo.AxPerson.Type
dbo.AxPerson.ShiftDesc,
dbo.TimeAttendance.EventTime,
) AS dT

TSQL Averaging over datepart

I have a table with a datetime column in it, consider it an event log for simple, analogous purposes.
I want to produce a report detailing the average number of events that occur at each time of day, to 30 min accuracy.
so the logic is,
get just the time component of each date
round the time to the nearest 30 min window (it can be floored, i.e. 00:29 -> 00:00)
count these (grouped by date)
average all these counts over all days
I also don't want to have any time holes in my data, for example, if nothing occurred in the 00:00 - 00:30 range, i want to report a 0, rather than having a missing row.
How can I achieve this?
WITH TestDates (date) AS (
SELECT CONVERT(DATETIME, '2011-11-15 10:00') UNION ALL
SELECT CONVERT(DATETIME, '2011-11-15 11:31') UNION ALL
SELECT CONVERT(DATETIME, '2011-11-16 10:00')
-- CTE to generate 4 million rows with a sequential integer starting at 0
), GeneratedRows (seq) AS (
SELECT ROW_NUMBER() OVER (ORDER BY N1.number) - 1
FROM master..spt_values AS N1
CROSS JOIN master..spt_values AS N2
WHERE N1.name IS NULL
AND N2.name IS NULL
), RoundedTestDates (date) AS (
SELECT CASE
-- Subtract the minute part
WHEN DATEPART(MINUTE, date) < 25 THEN DATEADD(MINUTE, -1 * DATEPART(MINUTE, date), date)
-- Subtract the minute part, then add an hour
WHEN DATEPART(MINUTE, date) >= 45 THEN DATEADD(HOUR, 1, DATEADD(MINUTE, -1 * DATEPART(MINUTE, date), date))
-- Subtract the minute part, then add an half-hour
ELSE DATEADD(MINUTE, 30, DATEADD(MINUTE, -1 * DATEPART(MINUTE, date), date))
END
FROM TestDates
)
SELECT rounded_date = GeneratedPeriod.date
, ocurrences = COUNT(RoundedTestDates.date)
FROM (SELECT DATEADD(MINUTE, 30 * seq, (SELECT MIN(date) FROM RoundedTestDates))
FROM GeneratedRows
) AS GeneratedPeriod (date)
LEFT JOIN RoundedTestDates
ON GeneratedPeriod.date = RoundedTestDates.date
WHERE GeneratedPeriod.date <= (SELECT MAX(date) FROM RoundedTestDates)
GROUP BY GeneratedPeriod.date
ORDER BY 1
Here is the code you need: (tested in sql2008 and works fine!)
-- Table with the 48 30mins periods of the day
CREATE TABLE #Periods
(
Num INT
)
DECLARE #idt INT
SET #idt = 1
WHILE (#idt <= 48)
BEGIN
INSERT INTO #Periods VALUES (#idt)
SET #idt = #idt + 1
END
--Average of the count for each period on all days.
SELECT DayTable.Num, AVG(CAST(DayTable.DayCount AS DECIMAL))
FROM
( --Total incidents for each interval on each day.
SELECT CAST(FLOOR(CAST(#MyLog.LogDate AS FLOAT)) AS DATETIME) AS DayWithOutTime,
#Periods.Num AS Num,
COUNT(#MyLog.ID) AS DayCount
FROM #Periods LEFT JOIN #MyLog
ON #Periods.Num = (DATEPART(hh, #MyLog.LogDate)*60 + DATEPART(mi,#MyLog.LogDate))/30
GROUP BY CAST(FLOOR(CAST(#MyLog.LogDate AS FLOAT)) AS DATETIME),
#Periods.Num
) AS DayTable
GROUP BY DayTable.Num
DROP TABLE #Periods
Where #NyLog is the table where your datetime is. It shows the count of incidences for each 30min period. The Period 1 is 00:00 -> 00:30 and Period 48 is 23:30 -> 24:00.
In sybase sql is something like this, in sql-server you might need to do some changes but not much :)
create procedure Test #startDay varchar(8), #endDay varchar(8)
as
declare #ocurrence int
declare #numberOfDays int
select #numberOfDays = 0
create table #intervals (
interval_hour int,
interval_min_minute int,
interval_max_minute int,
ocurrences int
)
create table #insertions (
hour int,
minute int
)
declare #hour int, #minute int
select #hour = 0
-- create the intervals
while (#hour <> 24)
begin
insert into #intervals values(#hour,0,29,0)
insert into #intervals values(#hour,30,59,0)
select #hour = #hour + 1
end
while(#startDay <> #endDay)
begin
insert into #insertions
select datepart(hh, *yourcolumn*), datepart(mm, *yourcolumn*) from *yourdb..yourtable* where convert(varchar(8), *yourcolumn*, 112) = #startDay
select #startDay = convert(varchar(8), dateadd(dd, 1, convert(datetime, #startDay, 112)), 112)
select #numberOfDays = #numberOfDays + 1
end
declare cursor1 cursor for
select hour, minute from #insertions
open cursor1
fetch cursor1 into #hour, #minute
while (##sqlstatus=0)
begin
update #intervals
set i.ocurrences = i.ocurrences + 1
from #intervals i
where interval_hour = #hour and #minute between interval_min_minute and interval_max_minute
fetch cursor1 into #hour, #minute
end
close cursor1
select interval_hour 'hour', interval_min_minute 'min minute', interval_max_minute 'max minute', ocurrences,
case when ocurrences > 0 then convert(float, ocurrences) / convert(float, #numberOfDays) else 0 end 'ocurrences average' from #intervals
drop table #intervals
drop table #insertions
go
What I've done is use an auxiliary table of numbers (a 1 column table with number 1 to 1 million) and join to it, adding the value of the number with the dateadd function to the midnight of the date.
since you want 30 minute intervals, then you want to use the dateadd(minute, number*30, yourdate) where number <= 48 (since there are 1440 minutes in a day)/30 = 48 intervals. This will create your time intervals.
Then simply count your occurrences that happen in between the time intervals.

MySQL group by intervals in a date range

I am going to be graphing netflow data stored in a MySQL database, and I need an efficient way to get the relevant data points. They records are stored with the date as an int for seconds since epoch. I Would like to be able to something like:
Select SUM(bytes) from table where stime > x and stime < Y
group by (10 second intervals)
Is there anyway to do this? or, would it be faster to handle it locally in python? even for a 500K row table?
EDIT
My Mistake, the time is stored as an unsigned double instead of an INT.
I'm currently using GROUP BY (FLOOR(stime / I)) where I is the desired interval.
You may be able to do this using integer division. Not sure of the performance.
Let I be your desired interval in seconds.
SELECT SUM(bytes), ((stime - X) DIV I) as interval
FROM table
WHERE (stime > X) and (stime < Y)
GROUP BY interval
Example, let X = 1500 and I = 10
stime = 1503 -> (1503 - 1500) DIV 10 = 0
stime = 1507 -> (1507 - 1500) DIV 10 = 0
stime = 1514 -> (1514 - 1500) DIV 10 = 1
stime = 1523 -> (1523 - 1500) DIV 10 = 2
Have you tried the following? Just devide the tyiem column by 10 and round the result down.
SELECT SUM(bytes)
FROM table
WHERE stime > x
AND stime < Y
GROUP BY ROUND(stime/10, -1)
I don't know wether the ROUND() function and grouping with function calls works in MySQL though, the above is T-SQL.
FLOOR in group by sometimes fails. it sometimes groups different times as one value for example when you divide the value with 3 but it doesn't do the same when you divide with 4, although the difference between these two values is far bigger than 3 or 4 which it should group as two different groups. Better cast it to unsigned after floor which works like:
CAST(FLOOR(UNIX_TIMESTAMP(time_field)/I) AS UNSIGNED INT)
The problem:
Sometimes GROUP BY FLOOR(UNIX_TIMESTAMP(time_field)/3) gives less groups compared to GROUP BY FLOOR(UNIX_TIMESTAMP(time_field)/4) which is mathematically shouldn't be possible.
SELECT sec_to_time(time_to_sec(datefield)- time_to_sec(datefield)%(10)) as intervals,SUM(bytes)
FROM table
WHERE where stime > x and stime < Y
group by intervals
I used suggestions from both answers and a coworker. End result is as follows:
Select FROM_UNIXTIME(stime), bytes
from argusTable_2009_10_22
where stime > (UNIX_TIMESTAMP()-600)
group by floor(stime /10)
I tried the rounding solution as well, but the results were inconsistent.
Chance
I did this a few time ago, so i created some function (with sql server, but i assume it's nearly the same) :
First I created a scalar function that return me the ID of a date depending on an interval and a date part (minute,hour,day,moth,year):
CREATE FUNCTION [dbo].[GetIDDate]
(
#date datetime,
#part nvarchar(10),
#intervalle int
)
RETURNS int
AS
BEGIN
-- Declare the return variable here
DECLARE #res int
DECLARE #date_base datetime
SET #date_base = convert(datetime,'01/01/1970',103)
set #res = case #part
WHEN 'minute' THEN datediff(minute,#date_base,#date)/#intervalle
WHEN 'hour' THEN datediff(hour,#date_base,#date)/#intervalle
WHEN 'day' THEN datediff(day,#date_base,#date)/#intervalle
WHEN 'month' THEN datediff(month,#date_base,#date)/#intervalle
WHEN 'year' THEN datediff(year,#date_base,#date)/#intervalle
ELSE datediff(minute,#date_base,#date)/#intervalle END
-- Return the result of the function
RETURN #res
END
Then I created a table function that returns me all the id betweend a date range :
CREATE FUNCTION [dbo].[GetTableDate]
(
-- Add the parameters for the function here
#start_date datetime,
#end_date datetime,
#interval int,
#unite varchar(10)
)
RETURNS #res TABLE (StartDate datetime,TxtStartDate nvarchar(50),EndDate datetime,TxtEndDate nvarchar(50),IdDate int)
AS
begin
declare #current_date datetime
declare #end_date_courante datetime
declare #txt_start_date nvarchar(50)
declare #txt_end_date nvarchar(50)
set #current_date = case #unite
WHEN 'minute' THEN dateadd(minute, datediff(minute,0,#start_date),0)
WHEN 'hour' THEN dateadd(hour, datediff(hour,0,#start_date),0)
WHEN 'day' THEN dateadd(day, datediff(day,0,#start_date),0)
WHEN 'month' THEN dateadd(month, datediff(month,0,#start_date),0)
WHEN 'year' THEN dateadd(year, datediff(year,0,dateadd(year,#interval,#start_date)),0)
ELSE dateadd(minute, datediff(minute,0,#start_date),0) END
while #current_date < #end_date
begin
set #end_date_courante =
case #unite
WHEN 'minute' THEN dateadd(minute, datediff(minute,0,dateadd(minute,#interval,#current_date)),0)
WHEN 'hour' THEN dateadd(hour, datediff(hour,0,dateadd(hour,#interval,#current_date)),0)
WHEN 'day' THEN dateadd(day, datediff(day,0,dateadd(day,#interval,#current_date)),0)
WHEN 'month' THEN dateadd(month, datediff(month,0,dateadd(month,#interval,#current_date)),0)
WHEN 'year' THEN dateadd(year, datediff(year,0,dateadd(year,#interval,#current_date)),0)
ELSE dateadd(minute, datediff(minute,0,dateadd(minute,#interval,#current_date)),0) END
SET #txt_start_date = case #unite
WHEN 'minute' THEN CONVERT(VARCHAR(20), #current_date, 100)
WHEN 'hour' THEN CONVERT(VARCHAR(20), #current_date, 100)
WHEN 'day' THEN REPLACE(CONVERT(VARCHAR(11), #current_date, 106), ' ', '-')
WHEN 'month' THEN REPLACE(RIGHT(CONVERT(VARCHAR(11), #current_date, 106), 8), ' ', '-')
WHEN 'year' THEN CONVERT(VARCHAR(20), datepart(year,#current_date))
ELSE CONVERT(VARCHAR(20), #current_date, 100) END
SET #txt_end_date = case #unite
WHEN 'minute' THEN CONVERT(VARCHAR(20), #end_date_courante, 100)
WHEN 'hour' THEN CONVERT(VARCHAR(20), #end_date_courante, 100)
WHEN 'day' THEN REPLACE(CONVERT(VARCHAR(11), #end_date_courante, 106), ' ', '-')
WHEN 'month' THEN REPLACE(RIGHT(CONVERT(VARCHAR(11), #end_date_courante, 106), 8), ' ', '-')
WHEN 'year' THEN CONVERT(VARCHAR(20), datepart(year,#end_date_courante))
ELSE CONVERT(VARCHAR(20), #end_date_courante, 100) END
INSERT INTO #res (
StartDate,
EndDate,
TxtStartDate,
TxtEndDate,
IdDate) values(
#current_date,
#end_date_courante,
#txt_start_date,
#txt_end_date,
dbo.GetIDDate(#current_date,#unite,#interval)
)
set #current_date = #end_date_courante
end
return
end
So if I want to count all the user added for each interval of 33 minutes :
SELECT count(id_user) , timeTable.StartDate
FROM user
INNER JOIn dbo.[GetTableDate]('1970-01-01',datedate(),33,'minute') as timeTable
ON dbo.getIDDate(user.creation_date,'minute',33) = timeTable.IDDate
GROUP BY dbo.getIDDate(user.creation_date,'minute',33)
ORDER BY timeTable.StartDate
:)

Difference of two date time in sql server

Is there any way to take the difference between two datetime in sql server?
For example, my dates are
2010-01-22 15:29:55.090
2010-01-22 15:30:09.153
So, the result should be 14.063 seconds.
Just a caveat to add about DateDiff, it counts the number of times you pass the boundary you specify as your units, so is subject to problems if you are looking for a precise timespan.
e.g.
select datediff (m, '20100131', '20100201')
gives an answer of 1, because it crossed the boundary from January to February, so even though the span is 2 days, datediff would return a value of 1 - it crossed 1 date boundary.
select datediff(mi, '2010-01-22 15:29:55.090' , '2010-01-22 15:30:09.153')
Gives a value of 1, again, it passed the minute boundary once, so even though it is approx 14 seconds, it would be returned as a single minute when using Minutes as the units.
SELECT DATEDIFF (MyUnits, '2010-01-22 15:29:55.090', '2010-01-22 15:30:09.153')
Substitute "MyUnits" based on DATEDIFF on MSDN
SELECT DATEDIFF(day, '2010-01-22 15:29:55.090', '2010-01-22 15:30:09.153')
Replace day with other units you want to get the difference in, like second, minute etc.
I can mention four important functions of MS SQL Server that can be very useful:
1) The function DATEDIFF() is responsible to calculate differences between two dates, the result could be "year quarter month dayofyear day week hour minute second millisecond microsecond nanosecond", specified on the first parameter (datepart):
select datediff(day,'1997-10-07','2011-09-11')
2) You can use the function GETDATE() to get the actual time and calculate differences of some date and actual date:
select datediff(day,'1997-10-07', getdate() )
3) Another important function is DATEADD(), used to convert some value in datetime using the same datepart of the datediff, that you can add (with positive values) or substract (with negative values) to one base date:
select DATEADD(day, 45, getdate()) -- actual datetime adding 45 days
select DATEADD( s,-638, getdate()) -- actual datetime subtracting 10 minutes and 38 seconds
4) The function CONVERT() was made to format the date like you need, it is not parametric function, but you can use part of the result to format the result like you need:
select convert( char(8), getdate() , 8) -- part hh:mm:ss of actual datetime
select convert( varchar, getdate() , 112) -- yyyymmdd
select convert( char(10), getdate() , 20) -- yyyy-mm-dd limited by 10 characters
DATETIME cold be calculated in seconds and one interesting result mixing these four function is to show a formated difference um hours, minutes and seconds (hh:mm:ss) between two dates:
declare #date1 datetime, #date2 datetime
set #date1=DATEADD(s,-638,getdate())
set #date2=GETDATE()
select convert(char(8),dateadd(s,datediff(s,#date1,#date2),'1900-1-1'),8)
... the result is 00:10:38 (638s = 600s + 38s = 10 minutes and 38 seconds)
Another example:
select distinct convert(char(8),dateadd(s,datediff(s, CRDATE , GETDATE() ),'1900-1-1'),8) from sysobjects order by 1
I tried this way and it worked. I used SQL Server version 2016
SELECT DATEDIFF(MILLISECOND,'2010-01-22 15:29:55.090', '2010-01-22 15:30:09.153')/1000.00;
Different DATEDIFF Functions are:
SELECT DATEDIFF(year, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(quarter, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(month, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(dayofyear, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(day, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(week, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(hour, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(minute, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(second, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(millisecond, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
Ref: https://learn.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql?view=sql-server-2017
Ok we all know the answer involves DATEDIFF(). But that gives you only half the result you may be after. What if you want to get the results in human-readable format, in terms of Minutes and Seconds between two DATETIME values?
The CONVERT(), DATEADD() and of course DATEDIFF() functions are perfect for a more easily readable result that your clients can use, instead of a number.
i.e.
CONVERT(varchar(5), DATEADD(minute, DATEDIFF(MINUTE, date1, date2), 0), 114)
This will give you something like:
HH:MM
If you want more precision, just increase the VARCHAR().
CONVERT(varchar(12), DATEADD(minute, DATEDIFF(MINUTE, date1, date2), 0), 114)
HH:MM.SS.MS
There are a number of ways to look at a date difference, and more when comparing date/times. Here's what I use to get the difference between two dates formatted as "HH:MM:SS":
ElapsedTime AS
RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) / 3600 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 3600 / 60 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 60 AS VARCHAR(2)), 2)
I used this for a calculated column, but you could trivially rewrite it as a UDF or query calculation. Note that this logic rounds down fractional seconds; 00:00.00 to 00:00.999 is considered zero seconds, and displayed as "00:00:00".
If you anticipate that periods may be more than a few days long, this code switches to D:HH:MM:SS format when needed:
ElapsedTime AS
CASE WHEN DATEDIFF(S, StartDate, EndDate) >= 359999
THEN
CAST(DATEDIFF(S, StartDate, EndDate) / 86400 AS VARCHAR(7)) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 86400 / 3600 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 3600 / 60 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 60 AS VARCHAR(2)), 2)
ELSE
RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) / 3600 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 3600 / 60 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 60 AS VARCHAR(2)), 2)
END
The following query should give the exact stuff you are looking out for.
select datediff(second, '2010-01-22 15:29:55.090' , '2010-01-22 15:30:09.153')
Here is the link from MSDN for what all you can do with datediff function .
https://msdn.microsoft.com/en-us/library/ms189794.aspx
Internally in SQL Server dates are stored as 2 integers. The first integer is the number of days before or after the base date (1900/01/01). The second integer stores the number of clock ticks after midnight, each tick is 1/300 of a second.
More info here
Because of this, I often find the simplest way to compare dates is to simply substract them. This handles 90% of my use cases. E.g.,
select date1, date2, date2 - date1 as DifferenceInDays
from MyTable
...
When I need an answer in units other than days, I will use DateDiff.
SELECT DATEDIFF(yyyy, '2011/08/25', '2017/08/25') AS DateDiff
It's gives you difference between two dates in Year
Here (2017-2011)=6 as a result
Syntax:
DATEDIFF(interval, date1, date2)
Use This for DD:MM:SS:
SELECT CONVERT(VARCHAR(max), Datediff(dd, '2019-08-14 03:16:51.360',
'2019-08-15 05:45:37.610'))
+ ':'
+ CONVERT(CHAR(8), Dateadd(s, Datediff(s, '2019-08-14 03:16:51.360',
'2019-08-15 05:45:37.610'), '1900-1-1'), 8)
So this isn't my answer but I just found this while searching around online for a question like this as well. This guy set up a procedure to calculate hours, minutes and seconds. The link and the code:
--Creating Function
If OBJECT_ID('UFN_HourMinuteSecond') Is Not Null
Drop Function dbo.UFN_HourMinuteSecond
Go
Exec(
'Create Function dbo.UFN_HourMinuteSecond
(
#StartDateTime DateTime,
#EndDateTime DateTime
) Returns Varchar(10)
As
Begin
Declare #Seconds Int,
#Minute Int,
#Hour Int,
#Elapsed Varchar(10)
Select #Seconds = ABS(DateDiff(SECOND ,#StartDateTime,#EndDateTime))
If #Seconds >= 60
Begin
select #Minute = #Seconds/60
select #Seconds = #Seconds%60
If #Minute >= 60
begin
select #hour = #Minute/60
select #Minute = #Minute%60
end
Else
Goto Final
End
Final:
Select #Hour = Isnull(#Hour,0), #Minute = IsNull(#Minute,0), #Seconds = IsNull(#Seconds,0)
select #Elapsed = Cast(#Hour as Varchar) + '':'' + Cast(#Minute as Varchar) + '':'' + Cast(#Seconds as Varchar)
Return (#Elapsed)
End'
)
declare #dt1 datetime='2012/06/13 08:11:12', #dt2 datetime='2012/06/12 02:11:12'
select CAST((#dt2-#dt1) as time(0))
PRINT DATEDIFF(second,'2010-01-22 15:29:55.090','2010-01-22 15:30:09.153')
select
datediff(millisecond,'2010-01-22 15:29:55.090','2010-01-22 15:30:09.153') / 1000.0 as Secs
result:
Secs
14.063
Just thought I'd mention it.
Sol-1:
select
StartTime
, EndTime
, CONVERT(NVARCHAR,(EndTime-StartTime), 108) as TimeDiff
from
[YourTable]
Sol-2:
select
StartTime
, EndTime
, DATEDIFF(hh, StartTime, EndTime)
, DATEDIFF(mi, StartTime, EndTime) % 60
from
[YourTable]
Sol-3:
select
DATEPART(hour,[EndTime]-[StartTime])
, DATEPART(minute,[EndTime]-[StartTime])
from
[YourTable]
Datepart works the best
Please check below trick to find the date difference between two dates
DATEDIFF(DAY,ordr.DocDate,RDR1.U_ProgDate) datedifff
where you can change according your requirement as you want difference of days or month or year or time.
CREATE FUNCTION getDateDiffHours(#fdate AS datetime,#tdate as datetime)
RETURNS varchar (50)
AS
BEGIN
DECLARE #cnt int
DECLARE #cntDate datetime
DECLARE #dayDiff int
DECLARE #dayDiffWk int
DECLARE #hrsDiff decimal(18)
DECLARE #markerFDate datetime
DECLARE #markerTDate datetime
DECLARE #fTime int
DECLARE #tTime int
DECLARE #nfTime varchar(8)
DECLARE #ntTime varchar(8)
DECLARE #nfdate datetime
DECLARE #ntdate datetime
-------------------------------------
--DECLARE #fdate datetime
--DECLARE #tdate datetime
--SET #fdate = '2005-04-18 00:00:00.000'
--SET #tdate = '2005-08-26 15:06:07.030'
-------------------------------------
DECLARE #tempdate datetime
--setting weekends
SET #fdate = dbo.getVDate(#fdate)
SET #tdate = dbo.getVDate(#tdate)
--RETURN #fdate
SET #fTime = datepart(hh,#fdate)
SET #tTime = datepart(hh,#tdate)
--RETURN #fTime
if datediff(hour,#fdate, #tdate) <= 9
RETURN(convert(varchar(50),0) + ' Days ' + convert(varchar(50),datediff(hour,#fdate, #tdate))) + ' Hours'
else
--setting working hours
SET #nfTime = dbo.getV00(convert(varchar(2),datepart(hh,#fdate))) + ':' +dbo.getV00(convert(varchar(2),datepart(mi,#fdate))) + ':'+ dbo.getV00(convert(varchar(2),datepart(ss,#fdate)))
SET #ntTime = dbo.getV00(convert(varchar(2),datepart(hh,#tdate))) + ':' +dbo.getV00(convert(varchar(2),datepart(mi,#tdate))) + ':'+ dbo.getV00(convert(varchar(2),datepart(ss,#tdate)))
IF #fTime > 17
begin
set #nfTime = '17:00:00'
end
else
begin
IF #fTime < 8
set #nfTime = '08:00:00'
end
IF #tTime > 17
begin
set #ntTime = '17:00:00'
end
else
begin
IF #tTime < 8
set #ntTime = '08:00:00'
end
-- used for working out whole days
SET #nfdate = dateadd(day,1,#fdate)
SET #ntdate = #tdate
SET #nfdate = convert(varchar,datepart(yyyy,#nfdate)) + '-' + convert(varchar,datepart(mm,#nfdate)) + '-' + convert(varchar,datepart(dd,#nfdate))
SET #ntdate = convert(varchar,datepart(yyyy,#ntdate)) + '-' + convert(varchar,datepart(mm,#ntdate)) + '-' + convert(varchar,datepart(dd,#ntdate))
SET #cnt = 0
SET #dayDiff = 0
SET #cntDate = #nfdate
SET #dayDiffWk = convert(decimal(18,2),#ntdate-#nfdate)
--select #nfdate,#ntdate
WHILE #cnt < #dayDiffWk
BEGIN
IF (NOT DATENAME(dw, #cntDate) = 'Saturday') AND (NOT DATENAME(dw, #cntDate) = 'Sunday')
BEGIN
SET #dayDiff = #dayDiff + 1
END
SET #cntDate = dateadd(day,1,#cntDate)
SET #cnt = #cnt + 1
END
--SET #dayDiff = convert(decimal(18,2),#ntdate-#nfdate) --datediff(day,#nfdate,#ntdate)
--SELECT #dayDiff
set #fdate = convert(varchar,datepart(yyyy,#fdate)) + '-' + convert(varchar,datepart(mm,#fdate)) + '-' + convert(varchar,datepart(dd,#fdate)) + ' ' + #nfTime
set #tdate = convert(varchar,datepart(yyyy,#tdate)) + '-' + convert(varchar,datepart(mm,#tdate)) + '-' + convert(varchar,datepart(dd,#tdate)) + ' ' + #ntTime
set #markerFDate = convert(varchar,datepart(yyyy,#fdate)) + '-' + convert(varchar,datepart(mm,#fdate)) + '-' + convert(varchar,datepart(dd,#fdate)) + ' ' + '17:00:00'
set #markerTDate = convert(varchar,datepart(yyyy,#tdate)) + '-' + convert(varchar,datepart(mm,#tdate)) + '-' + convert(varchar,datepart(dd,#tdate)) + ' ' + '08:00:00'
--select #fdate,#tdate
--select #markerFDate,#markerTDate
set #hrsDiff = convert(decimal(18,2),datediff(hh,#fdate,#markerFDate))
--select #hrsDiff
set #hrsDiff = #hrsDiff + convert(int,datediff(hh,#markerTDate,#tdate))
--select #fdate,#tdate
IF convert(varchar,datepart(yyyy,#fdate)) + '-' + convert(varchar,datepart(mm,#fdate)) + '-' + convert(varchar,datepart(dd,#fdate)) = convert(varchar,datepart(yyyy,#tdate)) + '-' + convert(varchar,datepart(mm,#tdate)) + '-' + convert(varchar,datepart(dd,#tdate))
BEGIN
--SET #hrsDiff = #hrsDiff - 9
Set #hrsdiff = datediff(hour,#fdate,#tdate)
END
--select FLOOR((#hrsDiff / 9))
IF (#hrsDiff / 9) > 0
BEGIN
SET #dayDiff = #dayDiff + FLOOR(#hrsDiff / 9)
SET #hrsDiff = #hrsDiff - FLOOR(#hrsDiff / 9)*9
END
--select convert(varchar(50),#dayDiff) + ' Days ' + convert(varchar(50),#hrsDiff) + ' Hours'
RETURN(convert(varchar(50),#dayDiff) + ' Days ' + convert(varchar(50),#hrsDiff)) + ' Hours'
END
For Me This worked Perfectly
Convert(varchar(8),DATEADD(SECOND,DATEDIFF(SECOND,LogInTime,LogOutTime),0),114)
and the Output is
HH:MM:SS which is shown accurately in my case.
Please try
DECLARE #articleDT DATETIME;
DECLARE #nowDate DATETIME;
-- Time of the ARTICLE created
SET #articleDT = '2012-04-01 08:10:16';
-- Simulation of NOW datetime
-- (in real world you would probably use GETDATE())
SET #nowDate = '2012-04-10 11:35:36';
-- Created 9 days ago.
SELECT 'Created ' + CAST(DATEDIFF(day, #articleDT, #nowDate) AS NVARCHAR(50)) + ' days ago.';
-- Created 1 weeks, 2 days, 3 hours, 25 minutes and 20 seconds ago.
SELECT 'Created '
+ CAST(DATEDIFF(second, #articleDT, #nowDate) / 60 / 60 / 24 / 7 AS NVARCHAR(50)) + ' weeks, '
+ CAST(DATEDIFF(second, #articleDT, #nowDate) / 60 / 60 / 24 % 7 AS NVARCHAR(50)) + ' days, '
+ CAST(DATEDIFF(second, #articleDT, #nowDate) / 60 / 60 % 24 AS NVARCHAR(50)) + ' hours, '
+ CAST(DATEDIFF(second, #articleDT, #nowDate) / 60 % 60 AS NVARCHAR(50)) + ' minutes and '
+ CAST(DATEDIFF(second, #articleDT, #nowDate) % 60 AS NVARCHAR(50)) + ' seconds ago.';
For MS SQL, you can convert the datetime value to a double value.
The integer part contains the number of days since 1900-01-01, the fractional part contains the time in hours.
So you can calculate date difference as:
cast(date1-date2 as FLOAT)