Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the time difference between two timestamps in mysql

I work on a MySQL database table that has a column containing timestamps (Ex. 2014-09-16 09:08:05) of the time I ping different hosts. My question is how could I calculate in minutes the difference between the first ping and the last one for specific hosts? Also how could I specify different timestamps for the start and the end of the difference mentioned above (instead of the first and last ping). Here is an example of the table:

|--|---------|-------------------|----|
|id|http_code|pingtime           |host|
|--|---------|-------------------|----|
|10|200      |2014-09-16 09:08:05|2   |
|--|---------|-------------------|----|
|11|200      |2014-09-16 10:07:05|1   |
|--|---------|-------------------|----|
|12|200      |2014-09-16 10:14:10|2   |
|--|---------|-------------------|----|

I hope that I've explain myself clear enough.

like image 458
MariusNV Avatar asked Sep 16 '14 07:09

MariusNV


People also ask

How to get difference between two timestamps in seconds in MySQL?

To get difference between two timestamps in seconds, use two in-built functions TIME_TO_SEC () and TIMEDIFF () in MySQL. The syntax is as follows −

How do I calculate the difference between two dates in MySQL?

To calculate the difference between two dates, MySQL offers us two different methods: TIMESTAMPDIFF and TIMEDIFF. Which you use depends how you want the resulting difference formatted. This method returns the difference between two dates in the units supplied as the first parameter.

How to find the difference between two timestamps in Excel?

The TIMESTAMPDIFF function returns the difference between two given timestamps (that is, one timestamp is subtracted from the other) for the specified date part interval (seconds, days, weeks, etc.). The value returned is an INTEGER, the number of these intervals between the two timestamps.

What is the use of timediff () function in MySQL?

MySQL TIMEDIFF () Function 1 Definition and Usage. The TIMEDIFF () function returns the difference between two time/datetime expressions. ... 2 Syntax 3 Parameter Values 4 Technical Details. From MySQL 4.0 5 More Examples


1 Answers

You could use the native TIMESTAMPDIFF function :

SELECT TIMESTAMPDIFF(<INTERVAL>,<timestampFrom>,<timestampTo>);

If you want to find the difference between the first and the last timestamp of a given host ID, here you are:

SELECT TIMESTAMPDIFF(MINUTE,MIN(pingtime),MAX(pingtime))
FROM yourTable
WHERE host = 2;
like image 130
Creaforge Avatar answered Nov 07 '22 21:11

Creaforge