1. 程式人生 > 實用技巧 >時間、日期、時間戳的相互轉換

時間、日期、時間戳的相互轉換

python中時間、日期、時間戳的轉換

原文連結:https://www.cnblogs.com/jfl-xx/p/8024596.html

1.簡介

在編寫程式碼時,往往涉及時間、日期、時間戳的相互轉換。

2.示例

# 引入模組
import time, datetime

2.1 str型別的日期轉換為時間戳

 1 # 字元型別的時間
 2 tss1 = '2013-10-10 23:40:00'
 3 # 轉為時間陣列
 4 timeArray = time.strptime(tss1, "%Y-%m-%d %H:%M:%S")
 5 print timeArray     
 6
# timeArray可以呼叫tm_year等 7 print timeArray.tm_year # 2013 8 # 轉為時間戳 9 timeStamp = int(time.mktime(timeArray)) 10 print timeStamp # 1381419600 11 12 13 # 結果如下 14 time.struct_time(tm_year=2013, tm_mon=10, tm_mday=10, tm_hour=23, tm_min=40, tm_sec=0, tm_wday=3, tm_yday=283, tm_isdst=-1) 15 2013 16 1381419600

2.2 更改str型別日期的顯示格式

 1 tss2 = "2013-10-10 23:40:00"
 2 # 轉為陣列
 3 timeArray = time.strptime(tss2, "%Y-%m-%d %H:%M:%S")
 4 # 轉為其它顯示格式
 5 otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
 6 print otherStyleTime  # 2013/10/10 23:40:00
 7 
 8 tss3 = "2013/10/10 23:40:00"
 9 timeArray = time.strptime(tss3, "%Y/%m/%d %H:%M:%S
") 10 otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) 11 print otherStyleTime # 2013-10-10 23:40:00

2.3 時間戳轉換為指定格式的日期

 1 # 使用time
 2 timeStamp = 1381419600
 3 timeArray = time.localtime(timeStamp)
 4 otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray)
 5 print(otherStyleTime)   # 2013--10--10 23:40:00
 6 # 使用datetime
 7 timeStamp = 1381419600
 8 dateArray = datetime.datetime.fromtimestamp(timeStamp)
 9 otherStyleTime = dateArray.strftime("%Y--%m--%d %H:%M:%S")
10 print(otherStyleTime)   # 2013--10--10 23:40:00
11 # 使用datetime,指定utc時間,相差8小時
12 timeStamp = 1381419600
13 dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
14 otherStyleTime = dateArray.strftime("%Y--%m--%d %H:%M:%S")
15 print(otherStyleTime)   # 2013--10--10 15:40:00

2.4 獲取當前時間並且用指定格式顯示

 1 # time獲取當前時間戳
 2 now = int(time.time())     # 1533952277
 3 timeArray = time.localtime(now)
 4 print timeArray
 5 otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray)
 6 print otherStyleTime    
 7 
 8 # 結果如下
 9 time.struct_time(tm_year=2018, tm_mon=8, tm_mday=11, tm_hour=9, tm_min=51, tm_sec=17, tm_wday=5, tm_yday=223, tm_isdst=0)
10 2018--08--11 09:51:17
11 
12 
13 # datetime獲取當前時間,陣列格式
14 now = datetime.datetime.now()
15 print now
16 otherStyleTime = now.strftime("%Y--%m--%d %H:%M:%S")
17 print otherStyleTime  
18 
19 # 結果如下:
20 2018-08-11 09:51:17.362986
21 2018--08--11 09:51:17