时间戳(timestamp)、时间字符串(datetimestr)、时间(datetime)之间的相互转换

总览

import time,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))))

时间戳(timestamp)、时间字符串(datetimestr)、时间(datetime)之间的相互转换

效率分析

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"))

时间戳(timestamp)、时间字符串(datetimestr)、时间(datetime)之间的相互转换

时间戳转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))

时间戳(timestamp)、时间字符串(datetimestr)、时间(datetime)之间的相互转换