MySql difference between two timestamps in Seconds?

后端 未结 3 1800
夕颜
夕颜 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: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
    

提交回复
热议问题