MySQL: Average Time Difference for Datetime Records

If your table contains two datetime columns for which you wish to calculate, and display in readable format, the average time difference for the entire table, the simplest (and probably fastest) way to achieve this is by doing the calculation in your SQL statement directly.

To achieve this you first work out the time difference between the two fields using the TIMESTAMPDIFF functionality (specifying seconds as the unit to work in). Then you run AVG across that result set which will group and return the average time difference for the table as whole. Finally, use SEC_TO_TIME to convert the average result (which is now in seconds) into a user friendly display string.

Putting this all together, you SQL statement should now look like this:

“SELECT SEC_TO_TIME ( AVG ( TIMESTAMPDIFF ( SECOND, `datetime1`,`datetime2`))) FROM tabletoprocess

… the output of which will be in the format 00:00:00

Nifty.

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials. Bookmark the permalink.
blog comments powered by Disqus