CURRENT_TIMESTAMP in milliseconds

2019-01-16 17:35发布

问题:

Is there any way to get milliseconds out of a timestamp in MySql or PostgreSql (or others just out of curiosity)?

SELECT CURRENT_TIMESTAMP
--> 2012-03-08 20:12:06.032572

Is there anything like this:

SELECT CURRENT_MILLISEC
--> 1331255526000

or the only alternative is to use the DATEDIFF from the era?

回答1:

To get the Unix timestamp in seconds in MySQL:

select UNIX_TIMESTAMP();

Details: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp

Not tested PostgreSQL, but according to this site it should work: http://www.raditha.com/postgres/timestamp.php

select round( date_part( 'epoch', now() ) );


回答2:

For MySQL (5.6+) you can do this:

SELECT ROUND(UNIX_TIMESTAMP(CURTIME(4)) * 1000)

Which will return (e.g.):

1420998416685 --milliseconds


回答3:

In mysql, it is possible to use the uuid function to extract milliseconds.

select conv( 
            concat(
                   substring(uid,16,3), 
                   substring(uid,10,4), 
                   substring(uid,1,8))
                   ,16,10) 
            div 10000 
            - (141427 * 24 * 60 * 60 * 1000) as current_mills
from (select uuid() uid) as alias;

Result:

+---------------+
| current_mills |
+---------------+
| 1410954031133 |
+---------------+

It also works in older mysql versions!

Thank you to this page: http://rpbouman.blogspot.com.es/2014/06/mysql-extracting-timstamp-and-mac.html



回答4:

The correct way of extracting miliseconds from a timestamp value on PostgreSQL accordingly to current documentation is:

SELECT date_part('milliseconds', current_timestamp);

--OR

SELECT EXTRACT(MILLISECONDS FROM current_timestamp);

with returns: The seconds field, including fractional parts, multiplied by 1000. Note that this includes full seconds.



回答5:

In Mysql 5.7+ you can execute

select current_timestamp(6)

for more details

https://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html



回答6:

Use:

Select curtime(4);

This will give you milliseconds.



回答7:

In PostgreSQL you can use :

SELECT extract(epoch from now());

on MySQL :

SELECT unix_timestamp(now());


回答8:

Here's an expression that works for MariaDB and MySQL >= 5.6:

SELECT (UNIX_TIMESTAMP(NOW()) * 1000000 + MICROSECOND(NOW(6))) AS unix_now_in_microseconds;

This relies on the fact that NOW() always returns the same time throughout a query; it's possible that a plain UNIX_TIMESTAMP() would work as well, I'm not sure based on the documentation. It also requires MySQL >= 5.6 for the new precision argument for NOW() function (MariaDB works too).



回答9:

None of these responses really solve the problem in postgreSQL, i.e :

getting the unix timestamp of a date field in milliseconds

I had the same issue and tested the different previous responses without satisfying result.

Finally, I found a really simple way, probably the simplest :

SELECT (EXTRACT (EPOCH FROM <date_column>::timestamp)::float*1000 as unix_tms
FROM <table>

namely :

  • We extract the pgSQL EPOCH, i.e. unix timestamp in floatting seconds from our column casted in timestamp prudence (in some complexe queries, pgSQL could trow an error if this cast isn't explicit. See )
  • then we cast it in float and multiply it by 1000 to get the value in milliseconds


回答10:

The main misunderstanding in MySQL with timestamps is that MySQL by default both returns and stores timestamps without a fractional part.

SELECT current_timestamp()  => 2018-01-18 12:05:34

which can be converted to seconds timestamp as

SELECT UNIX_TIMESTAMP(current_timestamp()) => 1516272429

To add fractional part:

SELECT current_timestamp(3) => 2018-01-18 12:05:58.983

which can be converted to microseconds timestamp as

SELECT CAST( 1000*UNIX_TIMESTAMP(current_timestamp(3)) AS UNSIGNED INTEGER) ts => 1516272274786

There are few tricks with storing in tables. If your table was created like

    CREATE TABLE `ts_test_table` (
      `id` int(1) NOT NULL,
      `not_fractional_timestamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

than MySQL will NOT store fractional part within it:

    id, not_fractional_timestamp
    1,  2018-01-18 11:35:12

If you want to add fractional part into your table, you need to create your table in another way:

    CREATE TABLE `ts_test_table2` (
      `id` int(1) NOT NULL,
      `some_data` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL,
      `fractional_timestamp` timestamp(3) NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

that leads to required result:

    id, some_data, fractional_timestamp
    1,  8,         2018-01-18 11:45:40.811

current_timestamp() function is allowed to receive value up to 6, but I've found out (at least in my installed MySQL 5.7.11 version on Windows) that fraction precision 6 leads to the same constant value of 3 digits at the tail, in my case 688

    id, some_data, fractional_timestamp
    1,  2,         2018-01-18 12:01:54.167688
    2,  4,         2018-01-18 12:01:58.893688

That means that really usable timestamp precision of MySQL is platform-dependent:

  • on Windows: 3
  • on Linux: 6


回答11:

Easiest way I found to receive current time in milliseconds in MySql:

SELECT (UNIX_TIMESTAMP(NOW(3)) * 1000)

Since MySql 5.6.



回答12:

I felt the need to continue to refine, so in MySQL:

Current timestamp in milliseconds:

floor(unix_timestamp(current_timestamp(3)) * 1000)

Timestamp in milliseconds from given datetime(3):

floor(unix_timestamp("2015-04-27 15:14:55.692") * 1000)

Convert timestamp in milliseconds to datetime(3):

from_unixtime(1430146422456 / 1000)

Convert datetime(3) to timestamp in milliseconds:

floor(unix_timestamp("2015-04-27 14:53:42.456") * 1000)


回答13:

In MariaDB you can use

SELECT NOW(4);

To get milisecs. See here, too.



回答14:

In PostgreSQL we use this approach:

SELECT round(EXTRACT (EPOCH FROM now())::float*1000)


回答15:

I faced the same issue recently and I created a small github project that contains a new mysql function UNIX_TIMESTAMP_MS() that returns the current timestamp in milliseconds.

Also you can do the following :

SELECT UNIX_TIMESTAMP_MS(NOW(3)) or SELECT UNIX_TIMESTAMP_MS(DateTimeField)

The project is located here : https://github.com/silviucpp/unix_timestamp_ms

To compile you need to Just run make compile in the project root.

Then you need to only copy the shared library in the /usr/lib/mysql/plugin/ (or whatever the plugin folder is on your machine.)

After this just open a mysql console and run :

CREATE FUNCTION UNIX_TIMESTAMP_MS RETURNS INT SONAME 'unix_timestamp_ms.so';

I hope this will help, Silviu



回答16:

Do as follows for milliseconds:

select round(date_format(CURTIME(3), "%f")/1000)

You can get microseconds by the following:

select date_format(CURTIME(6), "%f")