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