Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql difference between two timestamps in Seconds?

Is it possible to calculate difference between two timestamps in Mysql and get output result in seconds? like 2010-11-29 13:16:55 - 2010-11-29 13:13:55 should give 180 seconds.

Thank you

like image 716
Good Guy Avatar asked Nov 29 '10 02:11

Good Guy


People also ask

How do you find the difference in time between two timestamps?

The difference is calculated by subtracting the second operand from the first. The result is rounded down, with any remainder discarded. For example, 61 minutes is equal to 1 hour, and 59 minutes is equal to 0 hours.

How does MySQL calculate datetime difference?

MySQL TIMEDIFF() Function The TIMEDIFF() function returns the difference between two time/datetime expressions. Note: time1 and time2 should be in the same format, and the calculation is time1 - time2.

What is timestamp in MySQL?

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in up to microseconds (6 digits) precision.

What is the difference between timestamp in Unix and MySQL?

Learn MySQL from scratch for Data Science and Analytics In MySQL, UNIX TIMESTAMPS are stored as 32-bit integers. On the other hand MySQL TIMESTAMPS are also stored in similar manner but represented in readable YYYY-MM-DD HH:MM:SS format.


2 Answers

I do not think the accepted answer is a good universal solution!

This is because the UNIX_TIMESTAMP() function fails for DATEs before 1970-01-01 (and for dates in the far future using 32 bit integers). This may happen easily for the day of birth of many living people.

A better solution is:

SELECT TIMESTAMPDIFF(SECOND, '2010-11-29 13:13:55', '2010-11-29 13:16:55') 

Which can be modified to return DAY YEAR MONTH HOUR and MINUTE too!

like image 129
OderWat Avatar answered Sep 22 '22 00:09

OderWat


Use the UNIX_TIMESTAMP function to convert the DATETIME into the value in seconds, starting from Jan 1st, 1970:

SELECT UNIX_TIMESTAMP('2010-11-29 13:16:55') - UNIX_TIMESTAMP('2010-11-29 13:13:55') as output 

Result:

output ------- 180 

An easy way to deal with if you're not sure which value is bigger than the other -- use the ABS function:

SELECT ABS(UNIX_TIMESTAMP(t.datetime_col1) - UNIX_TIMESTAMP(t.datetime_col2)) as output 
like image 42
OMG Ponies Avatar answered Sep 20 '22 00:09

OMG Ponies