Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is any way to convert decimal to time in MySQL?

I created a field called 'hours_spent' in MySQL using the decimal datatype to store time. The values are stored like this 1.30, 2.30 etc... (for 1hr30min, 2hr30min).

I want to calculate the sum of various time values.

The sum of time is not what I expected: 1.30 + 2.30 = 3.60, whereas I expected 4.00.

I used the SUM function in MySQL to count the hours_spent field. If the values are 0.30 + 1.50 = 1.80, whereas I expected 2.20.

My first mistake was to use the decimal type instead of the time datatype, but I cannot change datatype.

So, is there any way to sum the time values and get result as I expect?

Thanks

like image 739
user1638026 Avatar asked Nov 27 '12 16:11

user1638026


People also ask

How do I convert time to seconds in MySQL?

The TIME_TO_SEC() function converts a time value into seconds.

How do you use timestamp?

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in up to microseconds (6 digits) precision.


1 Answers

I prepared you a demo at sqlfiddle, you can try it there if you want:

http://www.sqlfiddle.com/#!2/c9afc/2

Here are the query samples:

select @indexer:=instr(dateasdecimal, '.')
, left(dateasdecimal, @indexer-1) * 60 + substr(dateasdecimal, @indexer+1)  as totalMinutes
from testtable;

select @indexer:=instr(dateasdecimal, '.')
, sum(left(dateasdecimal, @indexer-1) * 60 + substr(dateasdecimal, @indexer+1))  as totalMinutes
from testtable;

Note: Please don't forget to accept answers to your questions: https://meta.stackexchange.com/a/65088/200585

like image 144
Nesim Razon Avatar answered Sep 25 '22 20:09

Nesim Razon