自学内容网 自学内容网

Mysql DATETIME与TIMESTAMP的区别

TIMESTAMP的取值范围小,并且TIMESTAMP类型的日期时间在存储时会将当前时区的日期时间值转换为时间标准时间值,检索时再转换回当前时区的日期时间值。

而DATETIME则只能反映出插入时当地的时区,其他时区的人查看数据必然会有误差的。

DATETIME:日期时间,8字节。格式为YYYY-MM-DD HH:MM:SS,取值范围1000-01-01 00:00:00 至 9999-12-31 23:59:59

TIMESTAMP:时间戳,4字节。格式为YYYY-MM-DD HH:MM:SS,取值范围1970-01-01 00:00:01 UTC 至 2038-01-19 03:14:07 UTC

创建一张表,包含2种数据类型。如下:

mysql> create table tb_datetime(
    -> num1 datetime,
    -> num2 timestamp);
Query OK, 0 rows affected (1.25 sec)

mysql> desc tb_datetime;
+-------+-----------+------+-----+---------+-------+
| Field | Type      | Null | Key | Default | Extra |
+-------+-----------+------+-----+---------+-------+
| num1  | datetime  | YES  |     | NULL    |       |
| num2  | timestamp | YES  |     | NULL    |       |
+-------+-----------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> insert into tb_datetime values ('2023-2-28 21:21:12','2023-2-28 21:21:12');
Query OK, 1 row affected (0.14 sec)

mysql> select * from tb_datetime;
+---------------------+---------------------+
| num1                | num2                |
+---------------------+---------------------+
| 2023-02-28 21:21:12 | 2023-02-28 21:21:12 |
+---------------------+---------------------+
1 row in set (0.00 sec)

这个时候看到的数据是一样的。

接着,修改时区信息:

mysql> set time_zone = "+9:00";
Query OK, 0 rows affected (0.00 sec)

mysql> select * from tb_datetime;
+---------------------+---------------------+
| num1                | num2                |
+---------------------+---------------------+
| 2023-02-28 21:21:12 | 2023-02-28 22:21:12 |
+---------------------+---------------------+
1 row in set (0.00 sec)

可以看到,num2即TIMESTAMP类型的数据,跟着时区变化了。


原文地址:https://blog.csdn.net/xharvard/article/details/136356590

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!