Many times I need to get the difference between two times on a MySQL table or even multiple tables. Here are couple ways to do that...
Here is one I wrote this week:
SELECT *, TIME_TO_SEC(TIMEDIFF(end, started)) as diff_sec
FROM my_table
WHERE `started` >= '2015-12-17 05:00:00' AND `started` <= '2015-12-17 06:00:00'
HAVING diff_sec > 5
Thanks to stack overflow for the examples:
http://stackoverflow.com/questions/3528219/mysql-how-to-get-the-difference-between-two-timestamps-in-seconds
I have a bash script that I run everyday against all our database tables to collect sizes and row counts. Part of the script is determining how long since the script last ran to collect all that information. I store that time difference with the data so I know that the growth happened in the last 24 hours. This is how I do it:
SET @time_diff=0;
SET @time_diff=(SELECT TIMESTAMPDIFF(MINUTE,MAX(ts1.time_created),stgts.time_created) as minutes_since_last_timestamp
FROM today_stats_table_a stgts
INNER JOIN yesterday_stats_table_a ts1 ON (stgts.table_name = ts1.table_name AND stgts.schema_name = ts1.schema_name AND stgts.server_name = ts1.server_name));
UPDATE today_stats_table_a stgts
SET stgts.minutes_since_last_timestamp = @time_diff;
Here is an amazing tutorial with examples on this page for using TIMESTAMPDIFF:
http://www.w3resource.com/mysql/date-and-time-functions/mysql-timestampdiff-function.php
And there lots of other functions that deal with time to play with also:
http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html
No comments:
Post a Comment