1、时间→字符串
date_format(日期datetime, 格式字符串str) ,str 为转换后的指定字符串格式:
select date_format(NOW(),'%Y-%m-%d %H:%i:%s')
select date_format(NOW(),'%Y%m%d %H:%i:%s')
2、字符串→时间
mysql的数据进行分析时,经常会遇到将业务意义为时间类型的变量定义为字符串的情况。如果我们需要按照时间维度进行分析的话,首先先要将字符串转换为时间类型。
str_to_date(字符串str,时间格式datetime) ,,其中,str为需要转换的字符串;format为str中时间的格式。
注意:str中必须包含年月日,时分秒可以不包含。
str_to_date('2019-01-20 16:01:45','%Y-%m-%d %H:%i:%s')
select STR_TO_DATE('2019','%Y%m%d %h%i%s');——没有月、日
select STR_TO_DATE('201901','%Y%m%d %h%i%s');——没有日
select STR_TO_DATE('20190101','%Y%m%d %h%i%s');
select STR_TO_DATE('2019010101','%Y%m%d %h%i%s');
select STR_TO_DATE('201901010101','%Y%m%d %h%i%s');
select STR_TO_DATE('20190101010101','%Y%m%d %h%i%s');
输出结果为:
null
null
2019-01-01 00:00:00
2019-01-01 01:00:00
2019-01-01 01:01:00
2019-01-01 01:01:01
另外,str的可以有不同的格式。例如:
select STR_TO_DATE('2019-01-01','%Y-%m-%d');
select STR_TO_DATE('2019/01/01','%Y/%m/%d');
select STR_TO_DATE('2019+01+01','%Y+%m+%d');
select STR_TO_DATE('2019*01*01','%Y*%m*%d');
输出结果为:
2019-01-01
2019-01-01
2019-01-01
2019-01-01
3、时间→时间戳
select unix_timestamp(now());
输出结果:1591152833
4、字符串→时间戳
select unix_timestamp('2020-06-03');
输出结果:1591113600
5、时间戳→字符串
select from_unixtime(1591113600,'%Y-%m-%d');
日期格式如下:
%M 月名字(January……December)
%W 星期名字(Sunday……Saturday)
%D 有英语前缀的月份的日期(1st, 2nd, 3rd, 等等。)
%Y 年, 数字, 4 位
%y 年, 数字, 2 位
%a 缩写的星期名字(Sun……Sat)
%d 月份中的天数, 数字(00……31)
%e 月份中的天数, 数字(0……31)
%m 月, 数字(01……12)
%c 月, 数字(1……12)
%b 缩写的月份名字(Jan……Dec)
%j 一年中的天数(001……366)
%H 小时(00……23)
%k 小时(0……23)
%h 小时(01……12)
%I 小时(01……12)
%l 小时(1……12)
%i 分钟, 数字(00……59)
%r 时间,12 小时(hh:mm:ss [AP]M)
%T 时间,24 小时(hh:mm:ss)
%S 秒(00……59)
%s 秒(00……59)
%p AM或PM
%w 一个星期中的天数(0=Sunday ……6=Saturday )
%U 星期(0……52), 这里星期天是星期的第一天
%u 星期(0……52), 这里星期一是星期的第一