官方文档没有我们习惯的日期格式。查了很多博客,日期时间戳的转换也是一种大概的得到结果的方法。日期时间和时间经常一起使用。两个模块混合使用,我个人觉得时间格式化应该不会那么麻烦,非得用两个模块才能支持吗?因此,我搜索了源码,总结了以下常用的日期时间戳转换方法。下面主要有3个元素(时间字符串、格式、Unix时间戳),可以将时间字符串转换为另一种时间格式,或者将时间字符串转换为时间戳,或者将时间戳转换为时间字符串。datetime和time模块,任意一个都可以转换。两个模块都列出了示例:#coding:utf-8fromdatetimeimportdatetimeimporttimes='2019-06-0716:30:10'f='%Y-%m-%d%H:%M:%S's2='FriJun716:30:102019'f2='%c'//时间字符串到时间戳,时间字符串s和格式对应//int(t)tointegert=datetime.strptime(s,f).timestamp()#1559856210.0t2=time.mktime(time.strptime(s,f))#1559856210.0t3=time.mktime(time.strptime(s2,f2))#1559856210.0t4=datetime.strptime(s2,f2).timestamp()#1559856210.0t5=datetime.strptime('2019-06-07','%Y-%m-%d').timestamp()#1559836800.0t6=datetime.strptime('06/07/19','%x').timestamp()#1559836800.0(06/07/2019,'%m/%d/%Y')print(t,t2,t3,t4,t5,t6,"\n")ut=1559896210#将时间戳转换为时间字符串d=datetime.fromtimestamp(ut)#2019-06-0716:30:10d2=time.strftime(f,time.localtime(ut))#2019-06-0716:30:10d3=time.ctime(ut)#FriJun716:30:102019d4=datetime.fromtimestamp(ut).ctime()#FriJun716:30:102019d5=time.strftime('%Y-%m-%d',time.localtime(ut))#2019-06-07(05:23:30,%H:%M:%S)d6=datetime.fromtimestamp(ut).date()#2019-06-07d7=datetime.fromtimestamp(ut).time()#16:30:10d8=time.strftime('%x',time.localtime(ut))#06/07/19d9=time.strftime('%X',time.localtime(ut))#16:30:10dd=datetime.fromtimestamp(ut).strftime('%x')#06/07/19[(16:30:10,%X),(FriJun716:30:102019,%c)]print(d,d2,d3,d4,d5,d6,d7,d8,d9,dd,"\n")#格式转换#Convert2019-06-0716:30:10toFriJun716:30:102019#(16:30:10,%X)transf=datetime.strptime(s,f).strftime(f2)#ConvertFriJun716:30:102019to2019-06-07#(2019-06-0716:30:10,%Y-%m-%d%H:%M:%S)transf2=datetime.strptime(s2,f2).strftime('%Y-%m-%d')#transfer2019-06-0716:30:10周五六月716:30:102019#(2019-06-0716:30:10,%Y-%m-%d%H:%M:%S)transf3=time.strftime('%c',time.strptime(s,f))#ConvertFriJun716:30:102019to2019-06-0716:30:10transf4=time.strftime(f,time.strptime(s2,f2))print(transf,transf2,transf3,transf4)
