Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert seconds to days, hours, minutes, seconds (MySQL)

Example:

seconds ="1015557";

Result should be:

11days 18h:05m:57s

How can do this in MySQL?

like image 546
Zameer Ahmed Avatar asked Dec 26 '16 11:12

Zameer Ahmed


5 Answers

select concat(
    format(floor(s / @day),0),
    'days ',
    time_format(sec_to_time(s % @day),'%Hh:%im:%ss') 
  ) formatted_date
from (select 1015557 s) t, (select @day = 3600 * 24);

produces:

+--------------------+                                                                                                                               
| days               |                                                                                                                               
+--------------------+                                                                                                                               
| 11days 18h:05m:57s |                                                                                                                               
+--------------------+
like image 69
Gurwinder Singh Avatar answered Nov 17 '22 19:11

Gurwinder Singh


You can use a query like this:

SELECT
  DATE_FORMAT(date('1970-12-31 23:59:59')
   + interval 1015557 second,'%j days %Hh:%im:%ss') as result;

sample

mysql>     SELECT
    ->       DATE_FORMAT(date('1970-12-31 23:59:59')
    ->        + interval 1015557 second,'%j days %Hh:%im:%ss') as result;
+----------------------+
| result               |
+----------------------+
| 011 days 18h:05m:57s |
+----------------------+
1 row in set (0,00 sec)

mysql>
like image 33
Bernd Buffen Avatar answered Nov 17 '22 18:11

Bernd Buffen


You can try this out:

SET @seconds = 1015557;
SELECT CONCAT(
            FLOOR(TIME_FORMAT(SEC_TO_TIME(@seconds), '%H') / 24), 'days ',
            MOD(TIME_FORMAT(SEC_TO_TIME(@seconds), '%H'), 24), 'h:',
            TIME_FORMAT(SEC_TO_TIME(@seconds), '%im:%ss')
        )
AS Result

Result should be:

11days 18h:05m:57s

Hopefully this helps!.

like image 29
Kent Aguilar Avatar answered Nov 17 '22 19:11

Kent Aguilar


SELECT *, 
CONCAT( FLOOR(sec/3600),"hour ", FLOOR(MOD(sec,3600)/60),"min",MOD(sec,60),"sec") 
FROM table_1
like image 38
steven Yang Avatar answered Nov 17 '22 19:11

steven Yang


If one is interested in fraction of seconds, the following combines the responses from Kent Aguilar and Steven Yang.

SELECT CONCAT(
  FLOOR(TIME_FORMAT(SEC_TO_TIME(@seconds), '%H') / 24), 'days ',
  MOD(TIME_FORMAT(SEC_TO_TIME(@seconds), '%H'), 24), 'h:',
  FLOOR(MOD(@seconds,3600)/60), 'm:',
  MOD(@seconds,60), 's'
) AS Result
like image 1
DanimalReks Avatar answered Nov 17 '22 18:11

DanimalReks