MySQL: cómo obtener la diferencia entre dos marcas de tiempo en segundos
¿Hay alguna forma de hacer una consulta en MySQL que me dé la diferencia entre dos marcas de tiempo en segundos, o tendría que hacerlo en PHP? Y si es así, ¿cómo lo haría?
4 answers
Podría utilizar el TIMEDIFF()
y el TIME_TO_SEC()
funciona de la siguiente forma:
SELECT TIME_TO_SEC(TIMEDIFF('2010-08-20 12:01:00', '2010-08-20 12:00:00')) diff;
+------+
| diff |
+------+
| 60 |
+------+
1 row in set (0.00 sec)
También podría utilizar el UNIX_TIMESTAMP()
función como @ Amber sugirió en otra respuesta:
SELECT UNIX_TIMESTAMP('2010-08-20 12:01:00') -
UNIX_TIMESTAMP('2010-08-20 12:00:00') diff;
+------+
| diff |
+------+
| 60 |
+------+
1 row in set (0.00 sec)
Si está utilizando el tipo de datos TIMESTAMP
, supongo que la solución UNIX_TIMESTAMP()
sería un poco más rápida, ya que los valores TIMESTAMP
ya están almacenados como un entero que representa el número de segundos desde la época (Fuente). Citando el docs :
Cuando se usa
UNIX_TIMESTAMP()
en una columnaTIMESTAMP
, la función devuelve directamente el valor de la marca de tiempo interna, sin conversión implícita de "string-to-Unix-timestamp".Tenga en cuenta que
TIMEDIFF()
tipo de datos devueltoTIME
.TIME
los valores pueden variar de '-838: 59:59' a '838:59: 59' (aproximadamente 34.96 días)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:24
Qué tal "TIMESTAMPDIFF":
SELECT TIMESTAMPDIFF(SECOND,'2009-05-18','2009-07-29') from `post_statistics`
Https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_timestampdiff
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-16 03:23:24
UNIX_TIMESTAMP(ts1) - UNIX_TIMESTAMP(ts2)
Si desea una diferencia sin signo, agregue un ABS()
alrededor de la expresión.
Alternativamente, puede usar TIMEDIFF(ts1, ts2)
y luego convertir el resultado de tiempo en segundos con TIME_TO_SEC()
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-20 04:35:40
Tenga en cuenta que la solución TIMEDIFF()
solo funciona cuando el datetimes
son menos de 35 días aparte!
TIMEDIFF()
devuelve un tipo de datos TIME
, y el valor máximo para el TIEMPO es 838:59: 59 horas (=34,96 días)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-09 21:15:01