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.
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 −
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.
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.
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With