MySQL how to convert Time to Decimal or How to Average Time

Hi all,

today I’ve came across with a problem that I wanted to average time, get the average from a field type TIME (00:00:00) with only a query. I’ve started thinking of going and start breaking that string into bits (hours, minutes and seconds), convert all to seconds than make that average.

But there is a simpler way, MySQL has some TIME functions that can help you there, like TIME_TO_SEC and SEC_TO_TIME.
The process is simple, use TIME_TO_SEC to convert time to seconds, average it (AVG) and then convert it back to SEC_TO_TIME, all in a single line. Something like this example:

SELECT
	SEC_TO_TIME(
		AVG(
			TIME_TO_SEC(average_time)
		)
	)
FROM
	works

Any questions or comments? Please post it bellow.

Exit mobile version