python获取系统时间函数_简单记录python的时间函数操作
1. time和datetime模塊
import datetime,time
2. 獲得當前時間
time.time() #獲得當前時間,返回float型
time.localtime([float time]) #獲得本地當前時間,返回time.struct_time類型
說明:struct_time是一個只讀的9元組,其中參數命名分別如下:
Index
Attribute
Values
0
tm_year
(for example, 1993)
1
tm_mon
range [1, 12]
2
tm_mday
range [1, 31]
3
tm_hour
range [0, 23]
4
tm_min
range [0, 59]
5
tm_sec
range [0, 61]
6
tm_wday
range [0, 6], Monday is 0
7
tm_yday
range [1, 366]
8
tm_isdst
0, 1 or -1; see below
技巧一:
那么,如果要進行如時間修改等操作,而struc_time是只讀的,如何改變某個時間點的值呢?
由于元組是不可改變的,而此時需要對localtime()的元組進行處理,元組是列表的另一形式,可以相互轉化,列表可以隨時修改,因而可以進行如下轉化:
ttTuple = time.localtime()
ttList = list(ttTuple) #轉化為列表
ttList[4] = 30 #如果您要對第四項tm_min進行修改,此時就可以了
..... #列表中值進行修改
ttTuple = tuple(ttList) #重新轉化為元組
strLocaltime = time.strftime("%Y-%m-%d %X",ttTuple) #轉化為2010-07-21 20:30:00
技巧二:
如何快速處理列表中的每一項數據,例如將列表中所有的整型轉化為str類型,并進行字符串處理?
具體地,例如給定一個浮點時間timer,輸出為一個格式為YYYY-mm-dd_hh-mm格式的字符串。
ttTuple = time.localtime(timer)
ttList = list(ttTuple)
strList = map(str,ttList) #將列表中的每項轉化為str類型, 但由于是由int轉化str
#單數的時間,1-9無法轉化為‘01’,‘02’形式,需要處理
for i in range(5):
if(len(strList[i])%2 != 0):
strList[i] = '0' + strList[i] #單數,則補上0
strTime = strList[0]+'-'+strList[1]+'-'+strList[2]+'_'+strList[3]+'-'+strList[4] #獲得目標格式
當然,或者可以利用strLocaltime = time.strftime(format,ttTuple)來解決,沒有校驗過,可以試試。當時腦袋短路了,只想到這個方法,主要是為了新學的map()函數能夠用上,高手請任意拍磚,咱新手一枚。
3.時間相互轉化
time.strftime(format,struc_time) #將元組轉化為用戶自定義的format格式,返回時間字符串
time.strptime(str,format) #將format格式的時間字符串str轉化為元組,返回struc_time類型
time.mktime(struc_time) #將元組轉化為float類型的時間,返回float類型
>>> import time
>>> print time.strftime( "%Y-%m-%d %X", time.localtime(123456789)
... )
1973-11-30 05:33:09
>>> from datetime import datetime
>>> print datetime.fromtimestamp(123456)
1970-01-02 18:17:36
技巧三:
由上述可見,利用floatTime = time.mktime(time.strptime(str,format))可以將時間字符串轉化為浮點型時間格式,便于進行時間計算.
技巧四:
常用的直接獲得當前時間方法:
now = str(datetime.fromtimestamp(time.mktime(time.localtime())))
print now
技巧五:
精確到毫秒的當前方法:
now = datetime.today()
print now
分享到:
2010-09-17 08:42
瀏覽 8583
評論
總結
以上是生活随笔為你收集整理的python获取系统时间函数_简单记录python的时间函数操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小米手机充电慢是怎么回事
- 下一篇: python 正则匹配 条件太多怎么办_