MySQL 8随机日期/时间生成

MySQL 8随机日期/时间生成

在学习过程中,经常需要准备时间日期数据,经常用到的随机日期时间生产脚本:

1. 生成24小时内时间

有微秒值

mysql> select sec_to_time(rand() * 86400);
+-----------------------------+
| sec_to_time(rand() * 86400) |
+-----------------------------+
| 21:56:22.705685             |
+-----------------------------+
1 row in set (0.00 sec)

2.生成一天内随机时间

floor取整秒
86400 是1天的秒数

mysql> select sec_to_time(floor(rand() * 86400));
+------------------------------------+
| sec_to_time(floor(rand() * 86400)) |
+------------------------------------+
| 08:44:18                           |
+------------------------------------+
1 row in set (0.00 sec)

3.生成1小时内时间

包括微秒

mysql> select sec_to_time(rand() * 3600);
+----------------------------+
| sec_to_time(rand() * 3600) |
+----------------------------+
| 00:04:40.939843            |
+----------------------------+
1 row in set (0.00 sec)

4.生成比当前时间小的90天内的随机日期

精确到天,注意负号 -90

mysql> SELECT date_add(current_date, interval rand() * -90 day) rand_date;
+------------+
| rand_date  |
+------------+
| 2023-10-14 |
+------------+
1 row in set (0.00 sec)

5.生成比当前时间大的90天内的随机日期

精确到天

mysql> SELECT date_add(current_date, interval rand() * 90 day) rand_date;
+------------+
| rand_date  |
+------------+
| 2023-12-03 |
+------------+
1 row in set (0.00 sec)

6.生成比当前时间小的90天内的随机时间

显示到秒实际精确到天

mysql> SELECT date_add(NOW(), interval rand() * -90 day) rand_date;
+---------------------+
| rand_date           |
+---------------------+
| 2023-10-07 11:06:14 |
+---------------------+
1 row in set (0.00 sec)

7.生成比当前时间小的90天内的随机时间

精确到微秒
90243600 = 7776000 ,90天的总秒数。

mysql> SELECT date_add(current_timestamp, interval rand() * -7776000 second);
+----------------------------------------------------------------+
| date_add(current_timestamp, interval rand() * -7776000 second) |
+----------------------------------------------------------------+
| 2023-10-27 23:40:25.021294                                     |
+----------------------------------------------------------------+
1 row in set (0.00 sec)

8.生成比当前时间小的90天内的随机时间

精确到秒格式化

mysql> SELECT DATE_FORMAT(date_add(current_timestamp, interval rand() * -7776000 second),'%Y-%m-%d %H:%i:%s');
+-------------------------------------------------------------------------------------------------+
| DATE_FORMAT(date_add(current_timestamp, interval rand() * -7776000 second),'%Y-%m-%d %H:%i:%s') |
+-------------------------------------------------------------------------------------------------+
| 2023-09-17 12:52:17                                                                             |
+-------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值