Python 將時間戳轉換為指定格式日期

Document 對象參考手冊 Python3 實例

給定一個時間戳,將其轉換為指定格式的時間。

注意時區的設置。

當前時間

實例 1

import time # 獲得當前時間時間戳 now = int(time.time()) #轉換為其他日期格式,如:"%Y-%m-%d %H:%M:%S" timeArray = time.localtime(now) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) print(otherStyleTime)

執行以上代碼輸出結果為:

2019-05-21 18:02:49

實例 2

import datetime # 獲得當前時間 now = datetime.datetime.now() # 轉換為指定的格式 otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S") print(otherStyleTime)

執行以上代碼輸出結果為:

2019-05-21 18:03:48

指定時間戳

實例 3

import time timeStamp = 1557502800 timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) print(otherStyleTime)

執行以上代碼輸出結果為:

2019-05-10 23:40:00

實例 4

import datetime timeStamp = 1557502800 dateArray = datetime.datetime.utcfromtimestamp(timeStamp) otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S") print(otherStyleTime)

執行以上代碼輸出結果為:

2019-05-10 23:40:00

Document 對象參考手冊 Python3 實例