Python日期/時間操作方法使用
0. 模組:
import os, sys
import time, datetime
1. 得到目前時間
(1) Based on time module:
import os, sys, time, datetime
startTime = time.localtime()
注意這裡: startTime
<type 'time.struct_time'>
(2) Based on datetime module:
import os, sys, time, datetime
nowTime = datetime.datetime.now()
type(nowTime)
<type 'datetime.datetime'>
2. 日期轉字串:
(1) str(xx)
(2) time提供的函數:
time.strftime([format], time)
strStartTime = time.strftime('%Y-%m-%d %H:%M:%S', startTime)
'2009-06-03 13:44:51'
3. 字串轉日期:
(1) 字串轉time:
d = time.strptime(strStartTime, '%Y-%m-%d %H:%M:%S')
(2009, 6, 3, 13, 44, 51, 2, 154, -1)
type(d)
<type 'time.struct_time'>
(2) 字串轉datetime
datetime的好處是可以實現方便的時間運算,比如 endTime - starTime,這在時間duration計算時非常方便.
# Convert string start time and end time to datetime.datetime
startTime = datetime.datetime(tmpStartTime[0], tmpStartTime[1], tmpStartTime[2], tmpStartTime[3], tmpStartTime[4], tmpStartTime[5] );
基於上面的轉換.