Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate difference between two datetimes in MySQL

Tags:

mysql

People also ask

How can I get the difference between two dates in MySQL?

To count the difference between dates in MySQL, use the DATEDIFF(enddate, startdate) function. The difference between startdate and enddate is expressed in days. In this case, the enddate is arrival and the startdate is departure .

How do I get the difference between two Datetimes in SQL?

To find the difference between dates, use the DATEDIFF(datepart, startdate, enddate) function. The datepart argument defines the part of the date/datetime in which you'd like to express the difference. Its value can be year , quarter , month , day , minute , etc.

How can I find the difference between two timestamps in MySQL?

To calculate the difference between the timestamps in MySQL, use the TIMESTAMPDIFF(unit, start, end) function. The unit argument can be MICROSECOND , SECOND , MINUTE , HOUR , DAY , WEEK , MONTH , QUARTER , or YEAR . To get the difference in seconds as we have done here, choose SECOND .

Can we subtract two dates in MySQL?

DATE_SUB() function in MySQL is used to subtract a specified time or date interval to a specified date and then returns the date. Parameter: This function accepts two parameters which are illustrated below : date – Specified date to be modified. value addunit – Here the value is date or time interval to subtract.


USE TIMESTAMPDIFF MySQL function. For example, you can use:

SELECT TIMESTAMPDIFF(SECOND, '2012-06-06 13:13:55', '2012-06-06 15:20:18')

In your case, the third parameter of TIMSTAMPDIFF function would be the current login time (NOW()). Second parameter would be the last login time, which is already in the database.


my two cents about logic:

syntax is "old date" - :"new date", so:

SELECT TIMESTAMPDIFF(SECOND, '2018-11-15 15:00:00', '2018-11-15 15:00:30')

gives 30,

SELECT TIMESTAMPDIFF(SECOND, '2018-11-15 15:00:55', '2018-11-15 15:00:15')

gives: -40


If your start and end datetimes are on different days use TIMEDIFF.

SELECT TIMEDIFF(datetime1,datetime2)

if datetime1 > datetime2 then

SELECT TIMEDIFF("2019-02-20 23:46:00","2019-02-19 23:45:00")

gives: 24:01:00

and datetime1 < datetime2

SELECT TIMEDIFF("2019-02-19 23:45:00","2019-02-20 23:46:00")

gives: -24:01:00


I don't think the accepted answer is appropriate. For example, if the difference between last login time and current time is 8 hours then getting the difference in seconds is illogical. The correct format will be in hours, minutes and seconds. I have illustrated this as follows -

Here, I create a table login_info table to store login information of users.

CREATE TABLE login_info (
    -> user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    -> last_login DATETIME NOT NULL,
    -> PRIMARY KEY (user_id)
    -> );

Then I populate the table using some random values -

INSERT INTO login_info (last_login) VALUES 
    -> ("2021-09-22 09:32:44"),
    -> ("2021-09-22 13:02:57"),
    -> ("2021-09-21 23:43:21"),
    -> ("2021-09-22 04:43:39"),
    -> ("2021-09-22 17:23:21");

Now I calculate the difference between last_login and current_time as follows:

CREATE TABLE login_dur_in_sec AS 
    -> SELECT user_id,
    -> TIMESTAMPDIFF(SECOND, last_login, NOW()) AS diff
    -> FROM login_info;
SELECT * FROM login_dur_in_sec;
+---------+-------+
| user_id | diff  |
+---------+-------+
|       1 | 28580 |
|       2 | 15967 |
|       3 | 63943 |
|       4 | 45925 |
|       5 |   343 |
+---------+-------+
CREATE TABLE hour_section AS 
    -> SELECT user_id,
    -> FLOOR (diff / 3600) AS hour_part 
    -> FROM login_dur_in_sec;
CREATE TABLE minute_section AS 
    -> SELECT user_id, 
    -> FLOOR (MOD (diff, 3600)/ 60) AS minute_part
    -> FROM login_dur_in_sec;
CREATE TABLE second_section AS
    -> SELECT user_id,
    -> MOD (MOD (diff, 3600), 60) AS second_part
    -> FROM login_dur_in_sec;
CREATE TABLE login_dur AS 
    -> SELECT h.user_id, h.hour_part, m.minute_part, s.second_part
    -> FROM hour_section AS h INNER JOIN minute_section AS m
    -> ON h.user_id = m.user_id
    -> INNER JOIN second_section AS s
    -> ON m.user_id = s.user_id;
CREATE TABLE login_dur_trunc AS 
    -> SELECT user_id,
    -> CONCAT (hour_part, ":", minute_part, ":", second_part) AS login_duration
    -> FROM login_dur;
SELECT * FROM login_dur_trunc;
+---------+----------------+
| user_id | login_duration |
+---------+----------------+
|       1 | 8:14:46        |
|       2 | 4:44:33        |
|       3 | 18:4:9         |
|       4 | 13:3:51        |
|       5 | 0:24:9         |
+---------+----------------+

Here, the answer given by @Adi won't work always as pointed out by @CaiusJard.