数据分析sql技能之时间处理
2017-07-21 本文已影响185人
采菊东篱下
本系列文章均为实际工作中遇到的场景,以此记录下来,共同进步,更愉悦的工作。
interval 关键字
查询 今天,昨天,一个月前 日期
mysql> select now() today, now() - interval 1 day yesterday;
+---------------------+---------------------+
| today | yesterday |
+---------------------+---------------------+
| 2017-07-21 14:50:12 | 2017-07-20 14:50:12 |
+---------------------+---------------------+
1 row in set (0.00 sec)
mysql> select now() - interval 1 month a, now() + interval -1 month b;
+---------------------+---------------------+
| a | b |
+---------------------+---------------------+
| 2017-06-21 14:54:02 | 2017-06-21 14:54:02 |
+---------------------+---------------------+
1 row in set (0.01 sec)
current_date(), convert_tz(dt, from_tz, to_tz) 函数
其中current_date获取今天的日期,convert_tz函数对某个时间进行时区转换,比如我们直接current_date获得的是北京时间,如果我们需要转换为UTC的时间,也就是从 ** "+08:00" -> "+00:00" **
mysql> select convert_tz(current_date(), '+08:00', '+00:00');
+------------------------------------------------+
| convert_tz(current_date(), '+08:00', '+00:00') |
+------------------------------------------------+
| 2017-07-20 16:00:00 |
+------------------------------------------------+
1 row in set (0.00 sec)
mysql> select current_date();
+----------------+
| current_date() |
+----------------+
| 2017-07-21 |
+----------------+
1 row in set (0.00 sec)
mysql> select convert_tz(now(), '+08:00', '+00:00');
+---------------------------------------+
| convert_tz(now(), '+08:00', '+00:00') |
+---------------------------------------+
| 2017-07-21 07:05:57 |
+---------------------------------------+
1 row in set (0.00 sec)
mysql 日期时间相关的函数参考
https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html