MySql difference between two timestamps in Seconds?

后端 未结 3 1798
夕颜
夕颜 2021-01-30 13:22

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.<

相关标签:
3条回答
  • 2021-01-30 13:33

    TIMESTAMPDIFF method only works with datetime format. If you want the difference between just two times like '11:10:00' minus '10:20:00' then use

    select TIME_TO_SEC('11:10:00')-TIME_TO_SEC('10:20:00')
    
    0 讨论(0)
  • 2021-01-30 13:40

    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!

    0 讨论(0)
  • 2021-01-30 13:48

    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
    
    0 讨论(0)
提交回复
热议问题