总览
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))))
效率分析
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"))
时间戳转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))