如何以秒为单位在 MySQL 中计算两个时间戳之间的差值?


要计算两个时间戳之间的差值(以秒为单位),请在 MySQL 中使用两个内置函数 TIME_TO_SEC() 和 TIMEDIFF()。语法如下所示: -

select time_to_sec(timediff(yourCoulnName1,yourCoulnName2)) as anyVariableName from yourTableName;

为理解上述概念,让我们首先创建一个表。创建一个表的查询。

mysql> create table TimeToSecond
   −> (
   −> MyTime timestamp,
   −> YourTime timestamp
   −> );
Query OK, 0 rows affected (0.48 sec)

现在,你可以在表中插入一些日期时间值。查询如下: -

mysql> insert into TimeToSecond values('2016-05-10 10:02:00','2016-05-10 10:00:00');
Query OK, 1 row affected (0.15 sec)

mysql> insert into TimeToSecond values('2016-05-10 10:06:00','2016-05-10 10:03:00');
Query OK, 1 row affected (0.24 sec)

mysql> insert into TimeToSecond values('2018-05-10 11:00:00','2018-05-10 10:00:00');
Query OK, 1 row affected (0.08 sec)

插入后,你可以通过 select 语句查看表中存在多少条记录。显示所有记录的查询如下: -

mysql> select *from TimeToSecond;

输出如下: -

+---------------------+---------------------+
| MyTime              | YourTime            |
+---------------------+---------------------+
| 2016-05-10 10:02:00 | 2016-05-10 10:00:00 |
| 2016-05-10 10:06:00 | 2016-05-10 10:03:00 |
| 2018-05-10 11:00:00 | 2018-05-10 10:00:00 |
+---------------------+---------------------+
3 rows in set (0.00 sec)

现在,让我们使用上面讨论过的语法来计算两个时间戳之间的差值(以秒为单位)。查询如下: -

mysql> select time_to_sec(timediff(MyTime,YourTime)) as DifferenceInSeconds from TimeToSecond;

输出如下: -

+---------------------+
| DifferenceInSeconds |
+---------------------+
|                 120 |
|                 180 |
|                3600 |
+---------------------+
3 rows in set (0.00 sec)

更新于:30-Jul-2019

680 次浏览

职业生涯的开端

完成课程,获得认证

开始
广告
© . All rights reserved.