I have the below query.
select cast(dateadd(minute, datediff(minute, TimeIn, TimeOut), 0) as time(0) )
I get the results from two columns in the format of hrs-min-seconds.
I would like it in the format of min only. So 02:47:00 will read 167.
SQL Server Query:
SELECT cast(substring('02:47:00',1,2) AS int)*60+
cast(substring('02:47:00',4,2) AS int)+
cast(substring('02:47:00',7,2) AS int)/60.0 AS minutes
MYSQL Query:
SELECT TIME_TO_SEC('02:47:00') / 60
Result:
| MINUTES |
-----------
| 167 |
declare #Time DATETIME = '01:05:00'
select ((DATEPART(HOUR, #Time)*60) + (DATEPART(MINUTE, #Time)))
For SQL Server (works for 2005 too):
select Datediff(mi,convert(datetime,'00:00:00',108), convert(datetime,'02:47:00',108))
Try this:
datediff(minute, 0, '02:47')
Expanding on Justin's answer. This allows for situations where hours is larger than 2 digits.
declare #time varchar(50) = '102:47:05'
SELECT cast(right(#time,2) AS int)+
cast(left(right(#time,5),2) AS int)*60+
cast(left(#time,len(#time)-6) AS int)*3600 AS seconds,
(cast(right(#time,2) AS int)+
cast(left(right(#time,5),2) AS int)*60+
cast(left(#time,len(#time)-6) AS int)*3600)/60.0 AS minutes
Result:
seconds minutes
----------- ---------------------------------------
370025 6167.083333
SELECT DATEDIFF(minute,CAST('00:00' AS TIME), CAST('02:47' AS TIME)) AS difference
Gives you:
| DIFFERENCE |
--------------
| 167 |
Unfortunately, if you want to use DATEPART function for values with more than 24 hours, you will receive an error:
Conversion failed when converting date and/or time from character string."
You can test it with this code:
declare #Time DATETIME = '32:00:00'
select ((DATEPART(HOUR, #Time)*60) + (DATEPART(MINUTE, #Time)))
To solve this, I worked with this another approach:
declare #tbl table(WorkHrs VARCHAR(8))
insert into #tbl(WorkHrs) values ('02:47:00')
insert into #tbl(WorkHrs) values ('32:00:00')
-- Sum in minutes
SELECT TRY_CAST(([HOURS] * 60) + [MINUTES] + ([SECOND] / 60) AS INT) as TotalInMinutes
FROM (
SELECT
-- Use this aproach to get separated values
SUBSTRING(WorkHrs,1,CHARINDEX(':',WorkHrs)-1) AS [HOURS],
SUBSTRING(WorkHrs,4,CHARINDEX(':',WorkHrs)-1) AS [MINUTES],
SUBSTRING(WorkHrs,7,CHARINDEX(':',WorkHrs)-1) AS [SECOND] -- probably you can ignore this one
FROM #tbl
)
tbl
-- Sum in seconds
SELECT TRY_CAST(([HOURS] * 3600) + ([MINUTES] * 60) + [SECOND] AS INT) as TotalInSeconds
FROM (
SELECT
-- Use this aproach to get separated values
SUBSTRING(WorkHrs,1,CHARINDEX(':',WorkHrs)-1) AS [HOURS],
SUBSTRING(WorkHrs,4,CHARINDEX(':',WorkHrs)-1) AS [MINUTES],
SUBSTRING(WorkHrs,7,CHARINDEX(':',WorkHrs)-1) AS [SECOND]
FROM #tbl
)
tbl
This code will return like this:
$time = '02:47:00';
$time = explode(":",$time);
$total = ($a[0]*60)+$a[1];
echo 'Minutes : '.$total;<br>
echo 'Seconds : '.$a[2];
Related
Want to calculate minutes between to columns with start_time and end_time as timestamp without zone for two customers types, and then averange the result for each.
I tried to use extract() by using the following statement, but can't get the right result:
select avg(duration_minutes)
from (
select started_at,ended_at, extract('minute' from (started_at - ended_at)) as duration_minutes
from my_data
where customer_type = 'member'
) avg_duration;
Result:
avg
0.000
This run sucessfuly in BQ using the following:
select avg(duration_minutes) from
(
select started_at,ended_at,
datetime_diff(ended_at,started_at, minute) as duration_minutes
from my_table
where customer_type = "member"
) avg_duration
Result:
f0_
21.46
Wondering what might be failing in postgres?
extract(minute from ...) extracts the field with the minutes from the interval. So if the interval is "1 hour 26 minutes and 45 seconds" the result would be 26 not 86.
To convert an interval to the equivalent number of minutes, extract the total number of seconds using extract(epoch ...) and multiply that with 60.
select avg(duration_minutes)
from (
select started_at,
ended_at,
extract(epoch from (started_at - ended_at)) * 60 as duration_minutes
from my_data
where customer_type = 'member'
) avg_duration;
Note that you can calculate the average of an interval without the need to convert it to minutes:
select avg(duration)
from (
select started_at,
ended_at,
started_at - ended_at as duration
from my_data
where customer_type = 'member'
) avg_duration;
Depending on how you use the result, returning an interval might be more useful. You can also convert that to minutes using:
extract(epoch from avg(duration)) * 60 as average_minutes
i'm creating a select that calculate the difference between two timestamps
here the code: (isn't necessary you understand tables below. Just follow the thread)
(select value from demo.data where id=q.id and key='timestampend')::timestamp
- (select value from demo.data where id=q.id and key='timestampstart')::timestamp) as durata
Look at this example, if you want easier:
select timestamp_end::timestamp - timestamp_start as duration
here the result:
// "durata" is duration
The problem is that the first timestamp is 2017-06-21 and the second is 2017-06-22 so we have 1 day and some hours of difference.
How can i do for show the result not like "1 day 02:06:41.993657" but "26:06:41.993657" without milliseconds (26:06:41)?
Update
I'm testing this query:
select id as ticketid,
(select value from demo.data where id=q.id and key = 'timestampstart')::timestamp as TEnd,
(select value from demo.data where id=q.id and key = 'timestampend')::timestamp as TStart,
(select
make_interval
(
0,0,0,0, -- years, months, weeks, days
extract(days from duration1)::int * 24 + extract(hours from duration1)::int, -- calculated hours (days * 24 + hours)
extract(mins from duration1)::int, -- minutes
floor(extract(secs from duration1))::int -- seconds, without miliseconds, thus FLOOR()
) as duration1
from
(
(select value from demo.data where id=q.id and key='timestampstart')::timestamp - (select value from demo.data where id=q.id and key='timestampend')::timestamp
) t(duration) as dur
from (select distinct id from demo.data) q
error is the same: [Err] ERROR: syntax error at or near "::"
there is an error on id = q.id
data table is like this:
You could use EXTRACT function and wrap it up with MAKE_INTERVAL and some math. It's pretty straight forward, since you pass each part of timestamp to it:
select
make_interval(
0,0,0,0, -- years, months, weeks, days
extract(days from durdata)::int * 24 + extract(hours from durdata)::int, -- calculated hours (days * 24 + hours)
extract(mins from durdata)::int, -- minutes
floor(extract(secs from durdata))::int -- seconds, without miliseconds, thus FLOOR()
) as durdata
from (
select '2017-06-22 02:06:41.993657'::timestamp - '2017-06-21'::timestamp
) t(durdata);
Output:
durdata
----------
26:06:41
You could wrap it up within a function to make it easy to work with.
There is no worry about timestamp - timestamp returning an output with precision to more than days, and thus losing you some information, because even calculation for different years would still return days and additional time part.
Example:
postgres=# select ('2019-06-22 01:03:05.993657'::timestamp - '2017-06-21'::timestamp) as durdata;
durdata
------------------------
731 days 01:03:05.993657
In Postgres, although interval data type allows having hours value greater than 23 (see https://www.postgresql.org/docs/9.6/static/functions-formatting.html), to_char() function will cut out days and will take only "hours within a day" if you put delta value to it and try to get 'HH24' value.
So, I ended up with such trick, combining to_char(...) with extract('epoch' from...) and then putting the concatinated value to another to_char():
with timestamps(ts1, ts2) as (
select
'2017-06-21'::timestamptz,
'2017-06-22 01:03:05.1212'::timestamptz
), res as (
select
round(extract('epoch' from ts2 - ts1) / 3600) as hours,
to_char(ts2 - ts1, 'MI:SS') as min_sec
from timestamps
)
select hours, min_sec, to_char(format('%s:%s', hours, min_sec)::interval, 'HH24:MI:SS')
from res;
The result is:
hours | min_sec | to_char
-------+---------+----------
25 | 03:05 | 25:03:05
(1 row)
You can define an SQL function to make using it easier:
create or replace function extract_hhmmss(timestamptz, timestamptz) returns interval as $$
with delta(i) as (
select
case when $2 > $1 then $2 - $1
else $1 - $2
end
), res as (
select
round(extract('epoch' from i) / 3600) as hours,
to_char(i, 'MI:SS') as min_sec
from delta
)
select
(
case when $2 < $1 then '-' else '' end
|| to_char(format('%s:%s', hours, min_sec)::interval, 'HH24:MI:SS')
)::interval
from res;
$$ language sql stable;
Example of usage:
[local]:5432 nikolay#test=# select extract_hhmmss('2017-06-21'::timestamptz, '2017-06-22 01:03:05.1212'::timestamptz);
extract_hhmmss
----------------
25:03:05
(1 row)
Time: 0.882 ms
[local]:5432 nikolay#test=# select extract_hhmmss('2017-06-22 01:03:05.1212'::timestamptz, '2017-06-21'::timestamptz);
extract_hhmmss
----------------
-25:03:05
(1 row)
Notice, that it will give an error if timestamps are provided in reverse order, but it's not really hard to fix. // Update: already fixed.
Below is my table and i am inserting data from my windows .Net application at every 1 Second Interval. i want to write query to fetch data from the table at every nth interval for example at every 5 second.Below is the query i am using but not getting result as required. Please Help me
CREATE TABLE table_1
(
timestamp_col timestamp without time zone,
value_1 bigint,
value_2 bigint
)
This is my query which i am using
select timestamp_col,value_1,value_2
from (
select timestamp_col,value_1,value_2,
INTERVAL '5 Seconds' * (row_number() OVER(ORDER BY timestamp_col) - 1 )
+ timestamp_col as r
from table_1
) as dt
Where r = 1
Use date_part() function with modulo operator:
select timestamp_col, value_1, value_2
from table_1
where date_part('second', timestamp_col)::int % 5 = 0
I have a PostgreSQL table with a field named effective_date and data type is integer(epoch date). What I want to do is to select only the entries that have an effective_date of my choice (I only want to query by the month). My query is below and the problem is, it is not returning anything although the table do have many entries that match the selection criteria.
$query = "select *
from ". $this->getTable() ."
where pay_stub_entry_name_id = 43
AND to_char(effective_date, 'Mon') = 'Jul'
AND deleted = 0";
Use extract(month from the_date) instead of to_char. See datetime functions in the Pg docs.
With to_char you'll suffer from all sorts of issues with case, localisation, and more.
Assuming you meant that the data type of effective_date was timestamp or date, you'd write:
$query = "select *
from ". $this->getTable() ."
where pay_stub_entry_name_id = 43
AND extract(month from effective_date) = 7
AND deleted = 0";
If it's integer then - assuming it's an epoch date - you have to convert it to a timestamp with to_timestamp, then use extract on it. See the epoch section in the documentation linked to above, eg:
$query = "select *
from ". $this->getTable() ."
where pay_stub_entry_name_id = 43
AND extract(month from to_timestamp(effective_date)) = 7
AND deleted = 0";
The immediate cause of your problem was that you were calling to_char(integer,text) with an integer epoch date. Only the timestamp versions of to_char do date formatting; Mon isn't special for the others, so it was simply output as a literal string Mon. Compare:
regress=# SELECT to_char(current_timestamp, 'Mon');
to_char
---------
Aug
(1 row)
regress=# select to_char( extract(epoch from current_timestamp), 'Mon');
to_char
---------
Mon
(1 row)
Remember to parameterise your real-world versions of these queries to help avoid SQL injection.
What is the best way to shorten a datetime that includes milliseconds to only have the second?
For example 2012-01-25 17:24:05.784 to 2012-01-25 17:24:05
This will truncate the milliseconds.
declare #X datetime
set #X = '2012-01-25 17:24:05.784'
select convert(datetime, convert(char(19), #X, 126))
or
select dateadd(millisecond, -datepart(millisecond, #X), #X)
CAST and CONVERT
DATEADD
DATEPART
The fastest, also language safe and deterministic
DATEADD(second, DATEDIFF(second, '20000101', getdate()), '20000101')
The easiest way now is:
select convert(datetime2(0) , getdate())
convert(datetime, convert(varchar, #datetime_var, 120), 120)
The following has very fast performance, but it not only removes millisecond but also rounds to minute. See (http://msdn.microsoft.com/en-us/library/bb677243.aspx)
select cast(yourdate as smalldatetime) from yourtable
Edit:
The following script is made to compare the scripts from Mikael and gbn I upvoted them both since both answers are great. The test will show that gbn' script is slightly faster than Mikaels:
declare #a datetime
declare #x int = 1
declare #mikaelend datetime
declare #mikael datetime = getdate()
while #x < 5000000
begin
select #a = dateadd(millisecond, -datepart(millisecond, getdate()), getdate()) , #x +=1
end
set #mikaelend = getdate()
set #x = 1
declare #gbnend datetime
declare #gbn datetime = getdate()
while #x < 5000000
begin
select #a = DATEADD(second, DATEDIFF(second, '20000101', getdate()), '20000101') , #x +=1
end
set #gbnend = getdate()
select datediff(ms, #mikael, #mikaelend) mikael, datediff(ms, #gbn, #gbnend) gbn
First run
mikael gbn
----------- -----------
5320 4686
Second run
mikael gbn
----------- -----------
5286 4883
Third run
mikael gbn
----------- -----------
5346 4620
declare #dt datetime2
set #dt = '2019-09-04 17:24:05.784'
select convert(datetime2(0), #dt)
Expanding on accepted answer by #Mikael Eriksson:
To truncate a datetime2(7) to 3 places (aka milliseconds):
-- Strip of fractional part then add desired part back in
select dateadd(nanosecond,
-datepart(nanosecond, TimeUtc) + datepart(millisecond, TimeUtc) * 1e6,
TimeUtc) as TimeUtc
The current max precision of datetime2(p) is (7) (from learn.microsoft.com)
--- DOES NOT Truncate milliseconds
--- 2018-07-19 12:00:00.000
SELECT CONVERT(DATETIME, '2018-07-19 11:59:59.999')
--- Truncate milliseconds
--- 2018-07-19 11:59:59.000
SELECT CONVERT(DATETIME, CONVERT(CHAR(19), '2018-07-19 11:59:59.999', 126))
--- Current Date Time with milliseconds truncated
SELECT CONVERT(DATETIME, CONVERT(CHAR(19), GETDATE(), 126))
SELECT CAST( LEFT( '2018-07-19 11:59:59.999' , 19 ) AS DATETIME2(0) )