How to use datediff function to show day, hour, minute, and second - sql

I have a record:
Depart_dt Arrived_dt
10/1/2013 6:15:00 AM 10/1/2013 7:25:00 AM
Based on my calculation, it is 0 day, one hour, and 10 minutes between the arrived_dt and Depart_dt. How do I show the result like below:
Day Hour Minute Second
0 1 10 0

You can use modulus division on the output of the DATEDIFF() function for this:
SELECT DATEDIFF(second,Depart_dt,Arrived_Dt)/(60*60*24) AS Day
,DATEDIFF(second,Depart_dt,Arrived_Dt)/(60*60)%24 AS Hour
,DATEDIFF(second,Depart_dt,Arrived_Dt)/(60)%60 AS Minute
,DATEDIFF(second,Depart_dt,Arrived_Dt)%60 AS Second
FROM Table1
Demo: SQL Fiddle

select
datediff(second,depart_dt, arrived_dt)/86400 as Day,
datediff(second,depart_dt, arrived_dt)/3600%24 as Hour,
datediff(second,depart_dt, arrived_dt)/60%60 as Minute,
datediff(second,depart_dt, arrived_dt)%60 as Second
from yourtable
Converting days, hours and minutes into seconds for accuracy.
SQL Fiddle: http://sqlfiddle.com/#!6/c6c63/1

Related

How to calculate the time difference in SQL with DATEDIFF?

I am using the DATEDIFF function to calculate the difference between my two timestamps.
payment_time = 2021-10-29 07:06:32.097332
trigger_time = 2021-10-10 14:11:13
What I have written is : date_diff('minute',payment_time,trigger_time) <= 15
I basically want the count of users who paid within 15 mins of the triggered time
thus I have also done count(s.user_id) as count
However it returns count as 1 even in the above case since the minutes are within 15 but the dates 10th October and 29th October are 19 days apart and hence it should return 0 or not count this row in my query.
How do I compare the dates in my both columns and then count users who have paid within 15 mins?
This also works to calculate minutes between to timestamps (it first finds the interval (subtraction), and then converts that to seconds (extracting EPOCH), and divides by 60:
extract(epoch from (payment_time-trigger_time))/60
In PostgreSQL, I prefer to subtract the two timestamps from each other, and extract the epoch from the resulting interval:
Like here:
WITH
indata(payment_time,trigger_time) AS (
SELECT TIMESTAMP '2021-10-29 07:06:32.097332',TIMESTAMP '2021-10-10 14:11:13'
UNION ALL SELECT TIMESTAMP '2021-10-29 00:00:14' ,TIMESTAMP '2021-10-29 00:00:00'
)
SELECT
EXTRACT(EPOCH FROM payment_time-trigger_time) AS epdiff
, (EXTRACT(EPOCH FROM payment_time-trigger_time) <= 15) AS filter_matches
FROM indata;
-- out epdiff | filter_matches
-- out ----------------+----------------
-- out 1616119.097332 | false
-- out 14.000000 | true

date_part doesn't count as a day if time difference is less

I calculate the day difference between 2 dates with date_part
DATE_PART('day', '2017-11-17 13:54:15' - '2017-11-12 18:05:18')
The day difference in here is 5 days when calculated.
However the sql returns as 4 since for the last day it has not been 24 hours.
But I would like to count it as 1 day.
How can I do this?
Here is one method:
DATE_PART('day'
date_trunc('day', '2017-11-17 13:54:15'::timestamp) - date_trunc('day', '2017-11-12 18:05:18'::timestamp)
)

how to show float numbers in Hours, Day, Minute, Second in SQL Server

I have a simple record in table below:
Depart_dt Arrived_dt
10/1/2013 6:15:00 AM 10/1/2013 7:25:00 AM
Based on my calculation, it is 1 hour and 10 min.
Thanks to VKP, I used the datediff function as below:
Select
Dateiff (DD, depart_dt, arrived_dt) as day,
Dateiff (HH, depart_dt, arrived_dt) as hour,
Dateiff (Minute, depart_dt, arrived_dt) as min,
Date if (second, depart_dt, arrived_dt) as second
from temp
However, my result looks funny with the minute and second columns
Day Hour Min Second
0 1 70 4200
The hour appears correct but I am not sure how it comes to 70 in min column and 4200 in second column?
sorry guys, I was wrong. Yes, 70 min is correct because that is 1 hour and 10 min. Please disregard this
You can just use DATEDIFF to get the difference as an integer.
select item,
datediff(dd, start_dt, end_dt) as total_days,
datediff(hh, start_dt, end_dt) as total_hours,
datediff(minute, start_dt, end_dt) as total_minutes,
datediff(second, start_dt, end_dt) as total_seconds
from yourtable
When using datediff you'll have to understand what it does. The name is quite confusing, because it doesn't actually calculate date differences, but according the documentation: "Returns the count (signed integer) of the specified datepart boundaries crossed between the specified startdate and enddate."
That means that for example datediff hour for 06:15 and 07:00 is 1 hour.
You'll probably want something like this:
DATEDIFF(SECOND, [Depart_dt], [Arrived_dt])/86400 as Days,
((DATEDIFF(SECOND, [Depart_dt], [Arrived_dt])%86400)/3600) as Hours,
(((DATEDIFF(SECOND, [Depart_dt], [Arrived_dt])%86400)%3600)/60) as Minutes,
(((DATEDIFF(SECOND, [Depart_dt], [Arrived_dt])%86400)%3600)%60) as Seconds
This calculates the amounts in full days / hours etc so number of hours will never be 24 or more.

Number of specific one-hour periods between two date/times

I have a table of table records, call it "game"
It has an id and timestamp.
What I need to know is unrelated to the table specifically. In order to know the average number of games played per hour, I need to know :
Total games played for each hour over the date range
Number of hourly
periods between the date range.
Finding the first is a matter of extracting the hour from the timestamp and grouping by it.
For the second, if the date range was rounded to the nearest day, finding this value would be easy (totalgames/numdays).
Unfortunately I can't assume this. What I need help with is finding the number of specific hour periods existing within a time range.
Example:
If the range is 5 PM today to 8 PM tomorrow, there is one "00" hour (midnight to 1 AM), but two 17, 18, 19 hours (5-6, 6-7, 7-8)
Thanks for the help
Edit: for clarity, consider the following query:
I have table game:
id, daytime
select EXTRACT(hour from daytime) as hour_period, count (*)
from game
where daytime > dateFrom and daytime < dayTo
group by hour_period
This will give me the number of games played broken down into hourly chunks for the time period.
In order to find the average games played per hour, I need to know exactly how many specific hour durations are between two timestamps. Simply dividing by the number of days is not accurate.
Edit: The ideal output will look something like this:
00 275
01 300
02 255
...
Consider the following: How many times does midnight occur between date 1 and date 2 ? If you have 1.5 days, that doesn't guarantee that midnight will occur twice. 6 AM today to 6 PM tomorrow night, for example, has 1 midnight, but 9PM tonight to 9 AM two days from now has 2 midnights.
What I'm trying to find is how many of the EXACT HOUR occurs between two timestamps, so I can use it to average the number of games played at THAT HOUR over a time period.
EDIT:
The following query gets the days, hours, and # of games, giving an output as below:
29 23 100
29 00 130
30 22 140
30 23 150
Then, the outer query adds up the number of games for each distinct hour and divides by the number of hours, as follows
22 140
23 125
00 130
The modified query is below:
SELECT
hour_period,
sum(hourly_no_of_games) / count(hour_period)
FROM
(
SELECT
EXTRACT(DAY from daytime) as day_period,
EXTRACT(HOUR from daytime) as hour_period,
count (*) hourly_no_of_games
from game
where daytime > dateFrom and daytime < dayTo
group by EXTRACT(DAY from daytime), EXTRACT(HOUR from daytime)
) hourly_data
GROUP BY hour_period
ORDER BY hour_period;
SQL Fiddle demo
If you need something to GROUP BY, you can truncate the timestamp to the level of hour, as in the following:
DECLARE #Date DATETIME
SET #Date = GETDATE()
SELECT #Date, DATEADD(Hour, DATEDIFF(Hour, 0, #Date), 0) AS RoundedDate
If you just need to find the total hours, you can just select the DATEDIFF in hours, such as with
SELECT DATEDIFF(Hour, '5/29/2014 20:01:32.999', GETDATE())
Extract not only the hour of the day but the day of the year (1-366). Then group on those. If there is the possibility the interval could span a year, then add the year itself and group by all three.
year dy hr games
2013 365 23 115
2014 1 00 103

SQL simple selection of rows according to their time

I have a table with measures and the time this measures have been taken in the following form: MM/DD/YYYY HH:MI:SS AM. I have measures over many days starting at the same time every day.The datas are minute by minute so basically the seconds are always = 0. I want to select only the measures for the first 5 minutes of each day. I would have used the where statement but the condition would only be on the minutes and note the date is there a way to do this?
Thanks
You could try something like this:
SELECT * FROM SomeTable
WHERE
DATEPART(hh, timestamp_col) = 0 AND -- filter for first hour of the day
DATEPART(mm, timestamp_col) <= 5 -- filter for the first five minutes
Careful! 0 means midnight. If your "first hour" of the day is actually 8 or 9 AM then you should replace the 0 with an 8 or 9.