1. 程式人生 > >時間戳(timestamp)、時間字串(datetimestr)、時間(datetime)之間的相互轉換

時間戳(timestamp)、時間字串(datetimestr)、時間(datetime)之間的相互轉換

總覽

# 時間戳轉時間字串(timestamp to datetimeStr)
def timestampToDateStr(stamps, frmt='%Y-%m-%d %H:%M:%S'):
#     return time.strftime(frmt, time.localtime(stamps))
    return datetime.fromtimestamp(stamps).strftime(frmt)

# 時間字串轉時間戳(datetimeStr to timestamp)
def dateStrToTimestamp(str_, frmt='%Y-%m-%d %H:%M:%S'
): # return time.mktime(datetime.strptime(str_, frmt).timetuple()) return time.mktime(time.strptime(str_, frmt)) # 時間字串轉時間(datetimeStr to datetime) def dateStrToDate(str_, frmt='%Y-%m-%d %H:%M:%S'): return datetime.strptime(str_, frmt) # 時間轉時間字串(datetime to datetimeStr) def dateToDateStr
(date_, frmt='%Y-%m-%d %H:%M:%S'): return date_.strftime(frmt) # 時間戳轉時間(datetime to timestamp) def timestampToDate(stamps): return datetime.fromtimestamp(stamps) # 時間轉時間戳(timestamp to datetime) 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(datetime.strptime(str_, frmt).timetuple())
    return time.mktime(time.strptime(str_, frmt))

# test
%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 datetime.fromtimestamp(stamps).strftime(frmt)
    return time.strftime(frmt, time.localtime(stamps))

# test
%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))

在這裡插入圖片描述