python 時間類型轉換,是我們經常遇到的問題,做下總結,記錄一下。(目前只有time模塊,有時間整理datetime)
1. 了解以下幾個時間概念:
- Timestamp(時間戳): 時間戳是指格林威治時間1970年01月01日00時00分00秒(北京時間1970年01月01日08時00分00秒)起至現在的總毫秒數(摘自百度百科)
- struct_time時間元組
- format time 格式化時間,已格式化的結構使時間更具可讀性。包括自定義格式和固定格式。
2. 關於time的常用方法
- 獲取當前時間,float類型
1 a_float = time.time() 2 print(a_float) 3 print(type(a_float))
- 將時間戳類型時間轉換為struct_time(時間元組) 的方法
- time.gmtime()
1 struct = time.gmtime(a_float)
2 print(struct)
3 print(type(struct))
#time.struct_time(tm_year=2018, tm_mon=12, tm_mday=3, tm_hour=3, tm_min=32, tm_sec=45, tm_wday=0, tm_yday=337, tm_isdst=0)
#time.struct_time()參數解釋:年,月,日,時,分,秒,周幾(0-6,0表示周日),一年中的第幾天,是否是夏令時(默認為-1)
- time.localtime()
1 localtime = time.localtime(time.time()) 2 print(localtime) 3 print(type(localtime))
- 將struct_time(時間元組)轉換為時間戳的方法
- time.mktime()
1 tempsTime = time.mktime(localtime) 2 print(tempsTime) 3 print(type(tempsTime))
- 將struct_time(時間元組)格式化為字符串的方法
- time.strftime( format [, t] )
- format 格式化時間字符串
- t 可選參數,為一個struct_time對象
代碼如下:
1 #將時間元組格式化為字符串 2 st_time = time.strftime('%Y-%m-%d',time.gmtime()) 3 print(st_time) 4 5 #%X 得到當前時間 6 local_time = time.strftime('%Y-%m-%d %X') 7 print(local_time) 8 print(type(local_time)) 9 10 #返回當地日期和時間 11 t = time.strftime('%x %X') 12 print(t) 13 print(type(t)) 14 #直接使用字符串拼接成為格式化時間字符串 15 tt = time.gmtime() 16 print(type(tt)) 17 print(str(tt.tm_year) + '年' + str(tt.tm_mon) + '月' + str(tt.tm_mday) + '日')
- time.strptime(string,format) 是將一個字符串格式日期,轉換為struct_time(時間元組)
- string 日期字符串
- format 格式化字符串‘
代碼如下:
1 #創建一個時間字符串變量strtime 2 strtime = "2018-01-13 22:20:30" 3 # ============================================================================= 4 # 通過strptime()函數將strtime轉化成strcut_time形式, 5 # 格式參數必須的"%Y-%m-%d %H:%M:%S",且必須strtime的時間參數一一匹配 6 # ============================================================================= 7 struct_tm = time.strptime(strtime,'%Y-%m-%d %H:%M:%S') 8 print(struct_tm) 9 print(type(struct_tm))
- time加減主要是通過時間戳的方式進行加減
a = time.time() b = time.time() print(a+b) print(b-a)