Python+常用模塊(2).md
阿新 • • 發佈:2018-04-13
any days hid 時間戳 _id 集合 tom soft oca
Python 常用模塊
1. random模塊
1.1 導入模塊
import random
1.2 random.random()
生成一個從0到1的隨機浮點數
1.3 random.uniform(10,20)
生成指點範圍內,也就是10到20(包括10和20,且位置可以互換)之間的隨機數
1.4 random.randint(a,b)
生成a到b之間的整數
1.5 random.randrange([start],stop[,step])
從指定集合中抽取隨機數,
1.6 random.choice(sequence)
從序列中獲取一個隨機元素,序列可以使list、字符串等.
與np.random.choice(a,size=None..)相比,只能抽一個
1.7 random.shuffle(x[,random])
x為列表,用於將列表打亂
1.8 random.sample(seqnence,k)
從制定序列中獲取指定長度的片段。
1.9 random.randint()
隨機整數
2. time模塊
2.1 導入模塊
import time
2.2 time.time()
返回當前時間戳
2.3 time.localtime()
格式化時間戳為本地時間
2.4 time.asctime(time.localtime)
接受時間元組並返回一個可讀的字符串
2.5 time.ctime()
時間戳轉化為asctime的格式,可讀
2.6 time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())
格式化時間元組
2.7 time.sleep()
進程掛起時間。
3. datetime模塊
3.1 導入模塊
import datetime
3.2 datetime.datetime.now()
獲取當前datetime
3.3 datetime.date.today()
獲取當天date,返回2018,4,8
3.4 獲取明天/前n天
datetime.date.today()+datatime.timedelta(days=1)
3.5 兩個datetime的時間差
相減返回時間戳
3.6 關系轉換
3.6.1 datetime->string
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
3.6.2 string->datetime
datetime.datetime.strptime("2014-12-31 18:20:10", "%Y-%m-%d %H:%M:%S")
3.6.3 datetime->timestamp
now = datetime.datetime.now()
timestamp = time.mktime(now.timetuple())
timestamp
3.6.3 timestamp->datetime
datetime.datetime.fromtimestamp(1421077403.0)
3.6.4 datetime->date
datetime.datetime.now().date()
3.6.5 date->datetime
today = datetime.date.today()
datetime.datetime.combine(today, datetime.time())
Python+常用模塊(2).md