Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL convert timediff output to day, hour, minute, second format

Tags:

mysql

This is my query:

SELECT TIMEDIFF(end_time,start_time) AS "total" FROM `metrics`;

which gives me:

116:12:10

meaning 116 hours, 12 minutes and 10 seconds.

Instead, I want it to say 4 days 20 hours, 12 minutes etc

like image 833
user656079 Avatar asked Mar 11 '11 22:03

user656079


People also ask

How do you convert seconds to HH MM SS in MySQL?

MySQL SEC_TO_TIME() Function The SEC_TO_TIME() function returns a time value (in format HH:MM:SS) based on the specified seconds.

How do I convert hours to minutes in MySQL?

mysql> SELECT t1, -> TIME_TO_SEC(t1) AS 'seconds', -> TIME_TO_SEC(t1)/60 AS 'minutes', -> TIME_TO_SEC(t1)/(60*60) AS 'hours', -> TIME_TO_SEC(t1)/(24*60*60) AS 'days' -> FROM time_val; +----------+---------+---------+-------+------+ | t1 | seconds | minutes | hours | days | +----------+---------+---------+-------+------ ...

How do I convert seconds to hours in MySQL?

MySQL SEC_TO_TIME() returns a time value by converting the seconds specified in the argument. The return value is in hours, minutes and seconds. The range of the result is in the time data type.

How do I change the date format in MySQL workbench?

Change the curdate() (current date) format in MySQL The current date format is 'YYYY-mm-dd'. To change current date format, you can use date_format().


2 Answers

SELECT CONCAT(
FLOOR(HOUR(TIMEDIFF('2010-01-06 08:46', '2010-01-01 12:30')) / 24), ' days ',
MOD(HOUR(TIMEDIFF('2010-01-06 08:46', '2010-01-01 12:30')), 24), ' hours ',
MINUTE(TIMEDIFF('2010-01-06 08:46', '2010-01-01 12:30')), ' minutes')

Use your end_time and start_time for the fixed datetime values in my example

As per the two comments below, this solution only works for date differences within 35 days. If you know there are more than 35 days between start and end, i.e. differences over a month, don't use it. Other answers here using TIMESTAMPDIFF will work.

like image 91
RichardTheKiwi Avatar answered Sep 17 '22 18:09

RichardTheKiwi


SELECT 
CONCAT(
TIMESTAMPDIFF(day,'2001-01-01 00:00:00','2001-01-02 23:10:00') , ' dagen ',
MOD( TIMESTAMPDIFF(hour,'2001-01-01 00:00:00','2001-01-02 23:10:00'), 24), ' uren ',
MOD( TIMESTAMPDIFF(minute,'2001-01-01 00:00:00','2001-01-02 23:10:00'), 60), ' minuten '
)
like image 25
borre Avatar answered Sep 20 '22 18:09

borre