MySql difference between two timestamps in days?

前端 未结 7 1152
既然无缘
既然无缘 2020-11-30 01:14

How can I get the difference between two timestamps in days? Should I be using a datetime column for this?


I switched my column to datetime. Simple subtraction doesn\'t
相关标签:
7条回答
  • 2020-11-30 01:25

    I know is quite old, but I'll say just for the sake of it - I was looking for the same problem and got here, but I needed the difference in days.

    I used SELECT (UNIX_TIMESTAMP(DATE1) - UNIX_TIMESTAMP(DATE2))/60/60/24 Unix_timestamp returns the difference in seconds, and then I just divide into minutes(seconds/60), hours(minutes/60), days(hours/24).

    0 讨论(0)
  • 2020-11-30 01:27
    CREATE TABLE t (d1 timestamp, d2 timestamp);
    
    INSERT INTO t VALUES ('2010-03-11 12:00:00', '2010-03-30 05:00:00');
    INSERT INTO t VALUES ('2010-03-11 12:00:00', '2010-03-30 13:00:00');
    INSERT INTO t VALUES ('2010-03-11 00:00:00', '2010-03-30 13:00:00');
    INSERT INTO t VALUES ('2010-03-10 12:00:00', '2010-03-30 13:00:00');
    INSERT INTO t VALUES ('2010-03-10 12:00:00', '2010-04-01 13:00:00');
    
    SELECT d2, d1, DATEDIFF(d2, d1) AS diff FROM t;
    
    +---------------------+---------------------+------+
    | d2                  | d1                  | diff |
    +---------------------+---------------------+------+
    | 2010-03-30 05:00:00 | 2010-03-11 12:00:00 |   19 |
    | 2010-03-30 13:00:00 | 2010-03-11 12:00:00 |   19 |
    | 2010-03-30 13:00:00 | 2010-03-11 00:00:00 |   19 |
    | 2010-03-30 13:00:00 | 2010-03-10 12:00:00 |   20 |
    | 2010-04-01 13:00:00 | 2010-03-10 12:00:00 |   22 |
    +---------------------+---------------------+------+
    5 rows in set (0.00 sec)
    
    0 讨论(0)
  • 2020-11-30 01:35

    If you need the difference in days accounting up to the second:

    SELECT TIMESTAMPDIFF(SECOND,'2010-09-21 21:40:36','2010-10-08 18:23:13')/86400 AS diff
    

    It will return
    diff
    16.8629

    0 讨论(0)
  • 2020-11-30 01:40

    SELECT DATEDIFF( now(), '2013-06-20' );

    here datediff takes two arguments 'upto-date', 'from-date'

    What i have done is, using now() function, i can get no. of days since 20-june-2013 till today.

    0 讨论(0)
  • 2020-11-30 01:44

    If you want to return in full TIMESTAMP format than try it: -

     SELECT TIMEDIFF(`call_end_time`, `call_start_time`) as diff from tablename;
    

    return like

         diff
         - - -
        00:05:15
    
    0 讨论(0)
  • 2020-11-30 01:45

    SELECT DATEDIFF(max_date, min_date) as days from my table. This works even if the col max_date and min_date are in string data types.

    0 讨论(0)
提交回复
热议问题