Using PostgreSQL database for my attendance application.
I have a table with IN and out times (hh:mm:ss.us format).
When I subtract the times (OUT -IN) to calculate the working hours, results are not as expected due to precision.
If IN Time is "22:12:56.09"
& OUT TIme is "22:14:06.06" the difference considering only HH:mm should be 00:02 but it actually shows "00:01:09.97" which becomes "00:01" in excel using only HH:mm.
I am trying to do the time conversion from hh:mm:ss.us to hh:mm (time format) so that I can subtract the time and get the desired output.
I have done similar things in SQL Server but I did not find any function in PostgreSQL. Please advise.
First you need to truncate the seconds. Then subtract to get desired result
select
to_char(
(
to_char('22:14:06.06' :: time, 'HH24:MI'):: time -
to_char('22:12:56.09' :: time, 'HH24:MI'):: time
),
'HH24:MI'
)
Result: 00:02
General Solution:
select
to_char(
(
to_char(out, 'HH24:MI'):: time - to_char(in, 'HH24:MI'):: time
),
'HH24:MI'
)
Here the purpose of to_char() is to format result to hours:minutes and not to include seconds.
Postgres includes seconds in interval by default.
You can use the date_trunc function with timestamp.
It would work something like this:
select date_trunc('minute', out) - date_trunc('minute', in)
This would set a minute level precision on the timestamp and convert HH:mm:ss to HH:mm:00
Related
I want to get truncked data over the last month. My time is in unix timestamps and I need to get data from last 30 days for each specific day.
The data is in the following form:
{
"id":"648637",
"exchange_name":"BYBIT",
"exchange_icon_url":"https://cryptowisdom.com.au/wp-content/uploads/2022/01/Bybit-colored-logo.png",
"trade_time":"1675262081986",
"price_in_quote_asset":23057.5,
"price_in_usd":1,
"trade_value":60180.075,
"base_asset_icon":"https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579",
"qty":2.61,
"quoteqty":60180.075,
"is_buyer_maker":true,
"pair":"BTCUSDT",
"base_asset_trade":"BTC",
"quote_asset_trade":"USDT"
}
I need to truncate data based on trade_time
How do I write the query?
The secret sauce is the date_trunc function, which takes a timestamp with time zone and truncates it to a specific precision (hour, day, week, etc). You can then group based on this value.
In your case we need to convert these unix timestamps javascript style timestamps to timestamp with time zone first, which we can do with to_timestamp, but it's still a fairly simple query.
SELECT
date_trunc('day', to_timestamp(trade_time / 1000.0)),
COUNT(1)
FROM pings_raw
GROUP BY date_trunc('day', to_timestamp(trade_time / 1000.0))
Another approach would be to leave everything as numbers, which might be marginally faster, though I find it less readable
SELECT
(trade_time/(1000*60*60*24))::int * (1000*60*60*24),
COUNT(1)
FROM pings_raw
GROUP BY (trade_time/(1000*60*60*24))::int
I recently switched to using postgreSQL and I am having same difficulties finding an alternative for timestampiff
My original query was something like
select a.column_a, a.column_b, TIMESTAMPDIFF(SQL_TSI_MINUTE, a.TIME_START, now()) AS "Time_diff"
from table as a
where
...
I can do just ( now() - a.TIME_START) but i want to show the result in minutes. Is there any better alternatives in postgresql to do the subtraction from now and show the result just as minutes ?
now() - a.TIME_START returns an interval which can be converted to seconds using extract() and those can be converted to minutes:
extract(epoch from now() - a.time_start) / 60 as diff_minutes
If you don't need it as a number, another option is to simply format the interval to show minutes and seconds
to_char(now() - a.time_start, 'mi:ss')
Note that this will hide the information if the interval was bigger than 60 minutes (or bigger than a day). If that can happen as well, maybe you want to use 'dd hh24:mi:ss' as a format mask instead
I have a time field which is storing numbers in '49235062'. Can these be converted to an actual readable time?
This does not look anything like a time stamp.
Thanks
Just a guess, but is this milliseconds from midnight?
Example
Select dateadd(MILLISECOND,49235062,0)
Returns
1900-01-01 13:40:35.063 -- 1:40 PM
If so, then it is a small matter to convert to time or format as time
Assuming that this is a UNIX timestamp (number of seconds since 1/1/1970), try the following:
DECLARE #timeStamp varchar(10) = '49235062'
SELECT #timeStamp, CONVERT(TIME, dateadd(S, CAST(#timeStamp AS int), '1970-01-01'))
Produces the following
49235062 20:24:22.0000000
So your time is 20:24:22 which is the answer that #pac0 suggested.
I have two timestamps and I would like to have a result with the difference between them. I found a similar question asked here but I have noticed that:
select
to_char(column1::timestamp - column2::timestamp, 'HH:MS:SS')
from
table
Gives me an incorrect return if these timestamps cross multiple days. I know that I can use EPOCH to work out the number of hours/days/minutes/seconds etc but my use case requires the result as a timestamp (or a string...anything not an interval!).
In the case of multiple days I would like to continue counting the hours, even if it should go past 24. This would allow results like:
36:55:01
I'd use the built-in date_part function (as previously described in an older thread: How to convert an interval like "1 day 01:30:00" into "25:30:00"?) but finally cast the result to the type you desire:
SELECT
from_date,
to_date,
to_date - from_date as date_diff_interval,
(date_part('epoch', to_date - from_date) * INTERVAL '1 second')::text as date_diff_text
from (
(select
'2018-01-01 04:03:06'::timestamp as from_date,
'2018-01-02 16:58:07'::timestamp as to_date)
) as dates;
This results in the following:
I'm currently unaware of any way to convert this interval into a timestamp and also not sure whether there is a use for it. You're still dealing with an interval and you'd need a point of reference in time to transform that interval into an actual timestamp.
I am converting an Unix script with a SQL transact command to a PostgreSQL command.
I have a table with records that have a field last_update_time(xtime) and I want to select every record in the table that has been updated within a selected period.
Say, the current time it 05/01/2012 10:00:00 and the selected time is 04/01/2012 23:55:00. How do I select all the records from a table that have been updated between these dates. I have converted the 2 times to seconds in the Unix script prior to issuing the psql command, and have calculated the interval in seconds between the 2 periods.
I thought something like
SELECT A,B,C FROM table
WHERE xtime BETWEEN now() - interval '$selectedtimeParm(in secs)' AND now();
I am having trouble evaluating the Parm for the selectedtimeParm - it doesn't resolve properly.
Editor's note: I did not change the inaccurate use of the terms period, time frame, time and date for the datetime type timestamp because I discuss that in my answer.
What's wrong with:
SELECT a,b,c
FROM table
WHERE xtime BETWEEN '2012-04-01 23:55:00'::timestamp
AND now()::timestamp;
If you want to operate with a count of seconds as interval:
...
WHERE xtime BETWEEN now()::timestamp - (interval '1s') * $selectedtimeParm
AND now()::timestamp;
Note the standard ISO 8601 date format YYYY-MM-DD h24:mi:ss which is unambiguous with any locale or DateStyle setting.
The first value for the BETWEEN construct must be the smaller one. If you don't know which value is smaller use BETWEEN SYMMETRIC instead.
In your question you refer to the datetime type timestamp as "date", "time" and "period". In the title you used the term "time frames", which I changed to "timestamps". All of these terms are wrong. Freely interchanging them makes the question even harder to understand.
That, and the fact that you only tagged the question psql (the problem hardly concerns the command line terminal) might help to explain why nobody answered for days. Normally, it's a matter of minutes around here. I had a hard time understanding your question.
Understand the data types date, interval, time and timestamp - with or without time zone. Start by reading the chapter "Date/Time Types" in the manual.
Error message would have gone a long way, too.
For anyone who is looking for the fix to this. You need to remove timestamp from the where clause and use BETWEEN!
TABLENAME.COL-NAME-FOR-TIMESTAMP BETWEEN '2020-01-29 04:18:00-06' AND CURRENT_TIMESTAMP