格式化时间和时间戳的转换

时间戳转换成格式化好的时间

#默认返回当前格式好的时间,如果传入时间戳的话,把时间戳转化成格式化好的时间

import time

def timestamp_to_fomat(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
    if timestamp:
        s=time.localtime(timestamp)
        date=time.strftime(format,s)
    else:
        date=time.strftime(format)
    return date

print(timestamp_to_fomat())
print(timestamp_to_fomat(timestamp=1550559940,format='%Y-%m'))

格式化好的时间转换成时间戳

import time
def strToTimestamp(str=None,format='%Y-%m-%d %H:%M:%S'):
    if str:
        tp=time.strptime(str,format)#转成时间元组
        res=time.mktime(tp)#转成时间戳
    else:
        res=time.time()#默认取当前时间戳
    return res
print(strToTimestamp())
print(strToTimestamp(str='2019-02-04',format='%Y-%m-%d'))

猜你喜欢

转载自www.cnblogs.com/ruijie/p/10402198.html
今日推荐