SQL Query to convert HHMM to minutes - mysql

I have a dataset that includes time columns in integer format as HHMM (i.e., 1730 means 5.30 PM). I would like to calculate the difference in time between rows in terms of minutes.
For example, the difference between 1730 (5.30 PM) and 1315 (1.15 PM) should result in 255 (as there are 4 hours and 15 mins difference)
Is there any way to make some calculations over time values in integer format to convert them to minutes?
So far I have tried the following to convert HHMM integer to minutes:
MOD(a,100) + (a DIV 100 ) * 60
But it does not work with error 'no viable alternative at input'.
Thanks in advance.

I have found a way to convert the number to minutes without changing the integer format. From minutes, you can do any operation between column values like this :
((a % 100) + (FLOOR(a/100)) *60)
Where a is an integer in the HHMM time format.
Hope this is helpful to others.
Best regards.

Related

How can I convert hh:mm:ss to float in sql?

SELECT SUM(render) AS total FROM mytable
This is my code for getting the summation of all rendered hrs. But the output turned out to be like for instance I have 04:30:00 and 03:15:00, then the output turned to 074520, but I want it to be like 7.75 hrs
Here is one way to do it in MySQL:
SELECT
SUM(HOUR(render) * 60.0 + MINUTE(render)) / 60.0 AS TotalHours
FROM mytable
The expression HOUR(render) * 60.0 + MINUTE(render) converts time value into the number of minutes which we sum up to get the total.
You can add SECOND() to the formula to get a more precise answer if you want.
If you want to sum a time type in MySQL, use:
select sum(time_to_sec(render))
from mytable;
This converts the time to a seconds value, sums the value, Then, if you want to convert it back to another format, convert the seconds:
select sum(time_to_sec(render)) / (60 * 60) as decimal_hours,
sec_to_time(sum(time_to_sec(render))) as time_format
MySQL does not directly sum time values. It is going to convert them to a number of the form HHMMSS. So, 00:00:55 is 55. If you add it to itself you get 110, which has nothing to do with 00:01:50.

Calculate the difference in hours between two String dates in MySQL?

I have two String columns in MySQL database. Those two columns were populated from a Java program in following way:
System.currentTimeMillis(); //first column
System.currentTimeMillis(); + someStringHours //second column; the String, someStringDays reprensents some number of days, let's say 5 hours in millis...
Which function in MySQL can be used to calculated the difference to get number of hours between these two columns?
You call them string dates but they are actually UNIX timestamps in milliseconds (also called Javascript timestamps). That's what System.currentTimeMillis() generates. It's a Java long data item, and a MySQL BIGINT data item. You can store it in a string. (You can store it that way if you must, but searching and sorting numbers stored as strings is an unreliable mess; beware!)
A typical Javascript timestamp (or UNIX timestamp in milliseconds) is a big integer like 1600858176374456. 1 600 858 176 374 456.
You can convert such a timestamp to a MySQL TIMESTAMP value with FROM_UNIXTIME() like this
FROM_UNIXTIME(column * 0.001)
Why multiply the column value by 0.001 (that is, divide it by 1000)? Because FROM_UNIXTIME() takes the timestamp in seconds, whereas System.currentTmeMillis() generates it in milliseconds.
Then you can use DATEDIFF() like this
DATEDIFF(FROM_UNIXTIME(laterTs*0.001),FROM_UNIXTIME(earlierTs*0.001))
This gives an integer number of days.
If you need the time difference in some other unit, such as hours, minutes, or calendar quarters, you can use TIMESTAMPDIFF(). This gives you your difference in hours.
TIMESTAMPDIFF(HOUR,
FROM_UNIXTIME(laterTs*0.001),
FROM_UNIXTIME(earlierTs*0.001));
You can use SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR as the time unit in this function.
Pro tip: Use your DBMS's date arithmetic functions if you possibly can. They've worked out all sorts of edge cases for you already.
And, by the way, if you declare your columns like this (Timestamp with a millisecond precision: How to save them in MySQL):
laterTs TIMESTAMP(3),
earlierTs TIMESTAMP(3),
You'll have an easier time indexing on and searching by these times.
SELECT (1600858176374-1600944576374)/(24*60*60*1000) as Days
Where (1600858176374-1600944576374) are timestamps and (246060*1000) is a mills in day

Is there a way to not to change type of varchar, when calculating time interval?

The type of data in column "length" is varchar.
I need to calculate average length of audio.
Do I need to change data type to datetime or is there a way not to do this?
I am afraid, if I do it , my values may become incorrect.
Thanks!
Example
Length
22:32:00
11:22:12
10:00:00
You should change the data type to time because in its current format you cannot do any time calculations on your data without converting it to time anyway.
As mysql manual on the time data type says:
TIME type can be used not only to represent a time of day (which must be less than 24 hours), but also elapsed time or a time interval between two events (which may be much greater than 24 hours, or even negative).
If you are worried about loosing some data due to incorrect formatting, then test varchar to time conversion using str_to_date() function. Wherever it returns null with the proper mask used, your data is in the wrong format.
Switch your data format to a number -- but the number of seconds of duration. You won't be limited to arbitrary limits on time and you can readily use the value for calculations.
If your length value is always 8 characters, you can do:
select (substring_index(length, ':', 1) * 60 * 60 +
substr(length, 4, 2) * 60 +
substring_index(length, ':', -1)
) as duration_seconds
If, after calculations, you want to represent the value as HH:MM:SS, you can convert back to that format.
The answer is no. It is like can you multiply YourNAme and HisName?
So it should be converted to a real number.
However, you can still do some addtion or multiplication using mysql syntax alone. The engine will implicitly convert it for you.
From your example, every row has hh:mm:ss, right? where : is the column separation?
If not yet separated, use substring or regex to separate it.
Assuming the hh, mm, and ss are separated.
You can actually perform arithmetic using SQL
SELECT
(SECONDS + MINUTES*60 + HOURS*60*60 ) as 'LengthInSeconds'
FROM yourTable
If you didn't want to separate to columns, just use substring or regex to separate during query.
You can now just sum all the queries and divide it by Ntimes
After you get the value. You convert it back to hours, minutes, and seconds. See sample code below.
//
$average = $totalAccumulatedSeconds/3;
// Time calculations for hours, minutes and seconds
$hours = Math.floor(($average % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
$minutes = Math.floor(($average % (1000 * 60 * 60)) / (1000 * 60));
$seconds = Math.floor(($average % (1000 * 60)) / 1000);
Actually you can perform several tests, if you really are afraid of calculations :)

What instead of CONVERT(TIME, x) Datepart?

I have complicated query over very big table.
Long story short, when I use convert time to select period of day (let's say 12-13h, converting it from datetime row) query takes few minutes, instead of few seconds without convert!
So, I tried datepart, and it works well, almost instant, but, problem is, how to point to hours and minutes in same time?
Any other fast solution is more than welcome.
Thanks.
Meanwhile I came up with this:
DATEPART(HOUR, datetimecolumn)*100 + DATEPART(MINUTE, datetimecolumn)) between 1210 and 1540
You can use datePart if you are willing to do a bit of math, as shown below:
12:10 = 12 * 60 + 10 = 730 minutes
15:40 = 15 * 60 + 40 = 940 minutes
select * .....
where datepart(mi, datefield) between (12*60+10) and (15*60+40)
If you have a constant periods - i.e. - always hourly and no any floating periods - you may introduce something like "ordinal number of period" calculated field, index on it and query of it with precalculated period value
OR
is there are no any constant periods - try to calculate proper begin and end values prior to SELECT statement and use them in the query.
Keep in mind that using functions in where clause of query - sometimes is a bad idea. Using functions in ORDER BY clause - always bad
You can get GETTIME from following Function
alter function GetTimeOnly(#_DateTime DateTime)
returns datetime
as
begin
return dateadd(day, -datediff(day, 0, #_datetime), #_datetime)
end
go
OR YOU CAN HAVE THE TIME FROM CONVERT FUNCTION.
SELECT
CONVERT(VARCHAR(8),GETDATE(),108) AS HourMinuteSecond,
CONVERT(VARCHAR(8),GETDATE(),101) AS DateOnly

Time Over 23:59:59 in PostgreSQL?

In MySQL I can create a table with a time field, and the value can be as high as 838:59:59 (839 hours - 1 second). I just read that in PostgreSQL, the hour field cannot exceed 23:00:00 (24 hours). Is there a way around this? I'm trying to make a simple DB that keeps track of how many hours & minutes were spent doing something, so it'll need to go higher than 23 hours & some minutes. I can do this in MySQL, but I need to use PostgreSQL for this. I Googled, but didn't find what I'm looking for, so I'm hoping I just didn't use the right keywords.
Postgres has no "hour field" - it has a few date/time types which serve different needs. The type I believe best fits your needs is INTERVAL.
Although they use the same notation, there's a difference between time of day and elapsed time. Some of their values overlap, but they're different domains. 838 isn't a valid value for an hour if you're talking about a time of day. 838 is a valid value for an hour if you're talking about elapsed time.
This distinction leads to two different data types: timestamp and interval.
create table intervals (
ts timestamp primary key,
ti interval not null
);
insert into intervals values (current_timestamp, '145:23:12');
select *
from intervals;
2011-08-03 21:51:16.837 145:23:12
select extract(hour from ti)
from intervals
145
I believe you are right, but It should not be an issue to work around. Would suggest storing the UNIX time integers for when you "punch in" and out again, and then adding the delta to an int field.
This will yield the number of seconds spent, which can be translated trivially into an hours:minutes:seconds format.
The delta (difference) can be calculated by subtracting the start timestamp from the end timestamp.
you could use a datetime field... 839 hours being something on the order 34.9 days...