python中的時間戳和格式化之間的轉換

2022-06-11 16:48:12 字數 800 閱讀 5594

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

時間戳格式化

1.格式化為yyyy mm dd hh mm ss形式的 public static string formatdatetime date date 2.格式化為 年 月 日 形式 public static string formatdate date mydate public static i...

時間戳格式化

獲取系統當前時間戳 long timestamp system.currenttimemillis 將時間戳轉化為date物件 date date new date timestamp 按指定格式生成解析物件 dateformat dateformat new dateformat yyyy年 mm...

時間戳格式化函式

時間戳格式化函式 param format 格式 param timestamp 要格式化的時間 預設為當前時間 return 格式化的時間字串 function timeshift timestamp,format if typeof timestamp string 如果時間戳後不是毫秒值就加0...