PostgreSQL创建自定义函数适配MySQL的unix_timestamp和from_unixtime函数

unix_timestamp

MySQL 中的 unix_timestamp() 函数返回自 1970 年 1 月 1 日 UTC 时间以来的秒数。在 PostgreSQL 中,可以通过 EXTRACTEPOCH 来获取这一信息。

CREATE OR REPLACE FUNCTION unix_timestamp(timestamp without time zone DEFAULT CURRENT_TIMESTAMP)
RETURNS bigint AS $$
BEGIN
  RETURN EXTRACT(EPOCH FROM COALESCE($1, CURRENT_TIMESTAMP))::bigint;
  -- RETURN date_part('epoch',COALESCE($1, CURRENT_TIMESTAMP))::bigint;
END;
$$ LANGUAGE plpgsql;

这个函数会接受一个时间戳参数,如果没有提供参数,则默认为当前时间。如果给定了时间戳,它会返回该时间戳自 1970 年 1 月 1 日以来的秒数。

MySQL示例

mysql> select now(),unix_timestamp(now());
+---------------------+-----------------------+
| now()               | unix_timestamp(now()) |
+---------------------+-----------------------+
| 2025-05-28 22:41:45 |            1748443305 |
+---------------------+-----------------------+
1 row in set (0.00 sec)

mysql> SELECT unix_timestamp('2025-05-28 10:00:00');
+---------------------------------------+
| unix_timestamp('2025-05-28 10:00:00') |
+---------------------------------------+
|                            1748397600 |
+---------------------------------------+
1 row in set (0.01 sec)

PostgreSQL示例

postgres=# select now(),unix_timestamp();
              now              | unix_timestamp 
-------------------------------+----------------
 2025-05-28 22:41:42.983955+08 |     1748443303
(1 row)

postgres=# SELECT unix_timestamp('2025-05-28 10:00:00');
 unix_timestamp 
----------------
     1748397600
(1 row)

from_unixtime

MySQL 中的 from_unixtime() 函数将一个 Unix 时间戳转换为日期和时间格式。在 PostgreSQL 中,可以使用 TO_TIMESTAMP 来完成这一操作。

CREATE OR REPLACE FUNCTION from_unixtime(bigint)
RETURNS timestamp without time zone AS $$
BEGIN
  RETURN TO_TIMESTAMP($1);
END;
$$ LANGUAGE plpgsql;

MySQL示例

mysql> select from_unixtime(1748404801,'%Y-%m-%d %T');
+-----------------------------------------+
| from_unixtime(1748404801,'%Y-%m-%d %T') |
+-----------------------------------------+
| 2025-05-28 12:00:01                     |
+-----------------------------------------+
1 row in set (0.00 sec)

PostgreSQL示例

postgres=# select from_unixtime(1748404801);
    from_unixtime    
---------------------
 2025-05-28 12:00:01
(1 row)

参考资料

善用mysql中的FROM_UNIXTIME()函数和UNIX_TIMESTAMP()函数

https://www.cnblogs.com/feiyun8616/p/12145212.html

posted @ 2025-05-28 22:52  kahnyao  阅读(118)  评论(0)    收藏  举报