CURRENT_TIMESTAMP in milliseconds

后端 未结 19 953
失恋的感觉
失恋的感觉 2020-12-07 23:48

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

SELECT CURRENT_TI         


        
19条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 00:30

    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

提交回复
热议问题