How can I get the total number of seconds since '1970-01-01 00:00:01'
from a DateTime instance in MySQL?
Asked
Active
Viewed 7.3k times
18

Jader Dias
- 88,211
- 155
- 421
- 625
4 Answers
36
You are looking for UNIX_TIMESTAMP()
.
See: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_unix-timestamp
If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC.

Sven Lilienthal
- 6,396
- 4
- 29
- 25
-
That converts a Datetime, which in general do not need to be UTC. If you need to convert a local Datetime, this answer must be edited. Check my answer. – Brethlosze Jul 05 '16 at 20:05
-
Also, as documentation says "The valid range of argument values is the same as for the TIMESTAMP data type: '1970-01-01 00:00:01.000000' UTC to '2038-01-19 03:14:07.999999' UTC. If you pass an out-of-range date to UNIX_TIMESTAMP(), it returns 0." – Oleksandr Jan 30 '21 at 17:33
6
UNIX_TIMESTAMP(datetime)
force a localization of the datetime, which unlike the timestamp, is stored "as is".
You need actually any of the following, for discarding the UTC correction:
UNIX_TIMESTAMP(CONVERT_TZ(datetime, '+00:00', @@session.time_zone))
or:
TIMESTAMPDIFF(SECOND,'1970-01-01 00:00:00',datetime)

Glorfindel
- 21,988
- 13
- 81
- 109

Brethlosze
- 1,533
- 1
- 22
- 41