python中的时间戳和格式化之间的转换

import time
#把格式化时间转换成时间戳

def str_to_timestamp(str_time=None, format='%Y-%m-%d %H:%M:%S'):
    if str_time:
        time_tuple = time.strptime(str_time, format)  # 把格式化好的时间转换成元祖
        result = time.mktime(time_tuple)  # 把时间元祖转换成时间戳
        return int(result)
    return int(time.time())


print(str_to_timestamp('2019-04-27 07:01:46'))
print(str_to_timestamp()) #1556349904


# 把时间戳转换成格式化

def timestamp_to_str(timestamp=None, format='%Y-%m-%d %H:%M:%S'):
    if timestamp:
        time_tuple = time.localtime(timestamp)  # 把时间戳转换成时间元祖
        result = time.strftime(format, time_tuple)  # 把时间元祖转换成格式化好的时间
        return result
    else:
        return time.strptime(format)

print(timestamp_to_str(1556348505)) #2019-04-27 15:01:45

  

猜你喜欢

转载自www.cnblogs.com/xiao-xue-di/p/11269767.html