17

How can I get the total number of seconds since '1970-01-01 00:00:01' from a DateTime instance in MySQL?

Jader Dias
  • 84,588
  • 150
  • 415
  • 615

4 Answers4

34

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,236
  • 4
  • 28
  • 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
7

Use UNIX_TIMESTAMP( dateField )

martin clayton
  • 74,574
  • 30
  • 214
  • 196
5
SELECT DATE_FORMAT(`value`, '%Y%m%d') AS `date_ymd` FROM `table_name`;
Pang
  • 9,073
  • 146
  • 84
  • 117
Orson
  • 14,383
  • 11
  • 52
  • 68
5

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)

Refs: 1, 2, 3, 4

Glorfindel
  • 20,880
  • 13
  • 75
  • 99
Brethlosze
  • 1,452
  • 17
  • 36