总览
import time,datetime
def timestampToDateStr(stamps, frmt='%Y-%m-%d %H:%M:%S'):
return datetime.fromtimestamp(stamps).strftime(frmt)
def dateStrToTimestamp(str_, frmt='%Y-%m-%d %H:%M:%S'):
return time.mktime(time.strptime(str_, frmt))
def dateStrToDate(str_, frmt='%Y-%m-%d %H:%M:%S'):
return datetime.strptime(str_, frmt)
def dateToDateStr(date_, frmt='%Y-%m-%d %H:%M:%S'):
return date_.strftime(frmt)
def timestampToDate(stamps):
return datetime.fromtimestamp(stamps)
def dateToTimestamp(date_):
return time.mktime(date_.timetuple())
dateStr = '2018-06-02 12:12:12'
stamps = 1527912732.0
lenth = 10
print(timestampToDateStr(stamps), type(timestampToDateStr(stamps)))
print(dateStrToTimestamp(dateStr), type(dateStrToTimestamp(dateStr)))
print(dateStrToDate(dateStr), type(dateStrToDate(dateStr)))
print(dateToDateStr(dateStrToDate(dateStr)), type(dateToDateStr(dateStrToDate(dateStr))))
print(timestampToDate(stamps), type(timestampToDate(stamps)))
print(dateToTimestamp(dateStrToDate(dateStr)), type(dateToTimestamp(dateStrToDate(dateStr))))
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1a0b2a7a1d080cbe3ddf73b68cd0e808.png)
效率分析
dateStr转时间戳
def dateStrToTimestamp(str_, frmt='%Y-%m-%d %H:%M:%S'):
return time.mktime(time.strptime(str_, frmt))
%timeit time.mktime(datetime.strptime("2014:06:28 11:53:21", "%Y:%m:%d %H:%M:%S").timetuple())
%timeit time.mktime(time.strptime("2014:06:28 11:53:21", "%Y:%m:%d %H:%M:%S"))
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e30b1049d03ad970c36387b42cacc73c.png)
时间戳转dateStr
def timestampToDateStr(stamps, frmt='%Y-%m-%d %H:%M:%S'):
return time.strftime(frmt, time.localtime(stamps))
%timeit datetime.fromtimestamp(1527912732.0).strftime('%Y-%m-%d %H:%M:%S')
%timeit time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1527912732.0))
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5cf10ce3d82cf838bc4fe830cbd49afb.png)