18

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

Jader Dias
  • 88,211
  • 155
  • 421
  • 625

4 Answers4

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
7

Use UNIX_TIMESTAMP( dateField )

martin clayton
  • 76,436
  • 32
  • 213
  • 198
7
SELECT DATE_FORMAT(`value`, '%Y%m%d') AS `date_ymd` FROM `table_name`;
Pang
  • 9,564
  • 146
  • 81
  • 122
Orson
  • 14,981
  • 11
  • 56
  • 70
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)

Refs: 1, 2, 3, 4

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Brethlosze
  • 1,533
  • 1
  • 22
  • 41