一,datetime
在python中datetime是一个库,是一个模块,也是一个函数,作用很多,这里面只对其做简单的最常用的讲解。
首先返回系统时间
#!/usr/bin/python3
import datetime
nowTime=datetime.datetime.now()
print (nowTime)
输出结果是: 2019-04-03 14:30:02.358785
返回当天日期
Today=datetime.date.today()
print(Today)
输出的结果是:2019-04-03
时间间隔(这是一个time模块,很有用的)
#!/usr/bin/python3
import time
def sleeptime(hour,min,sec):
return (hour*3600+min*60+sec);
sleep_time=sleeptime(0,0,3);
while 1==1:
time.sleep(sleep_time);
print ("每隔3秒显示一次")
输出结果是:
每隔3秒显示一次
每隔3秒显示一次
每隔3秒显示一次
二,random.seed()
random.seed()是随机数种子,也就是为随机数提供算法,完全相同的种子产生的随机数列是相同的,
所以如果想产生不同的随机数就需要用当前时间作为种子
#!/usr/bin/python3
import random
random.seed(0)
print ("Random number with seed 0 : ", random.random())
输出结果:Random number with seed 0 : 0.844421851525
#!/usr/bin/python3
import random
random.seed(0)
print ("Random number with seed 0 : ", random.random())
输出结果:Random number with seed 0 : 0.844421851525
#!/usr/bin/python3
import random
random.seed(0)
print ("Random number with seed 0 : ", random.random())
输出结果:Random number with seed 0 : 0.844421851525
以下为同时运行三个相同的随机种子
#!/usr/bin/python3
import random
random.seed(0)
print ("Random number with seed 0 : ", random.random())
random.seed(0)
print ("Random number with seed 0 : ", random.random())
random.seed(0)
print ("Random number with seed 0 : ", random.random())
输出结果:是相同的
Random number with seed 0 : 0.844421851525
Random number with seed 0 : 0.844421851525
Random number with seed 0 : 0.844421851525
以下为同时运行三个不同的随机种子
#!/usr/bin/python3
import random
random.seed(0)
print ("Random number with seed 0 : ", random.random())
random.seed(1)
print ("Random number with seed 0 : ", random.random())
random.seed(2)
print ("Random number with seed 0 : ", random.random())
输出结果:是不同的
Random number with seed 0 : 0.844421851525
Random number with seed 1 : 0.134364244112
Random number with seed 2 : 0.956034271889
所以如果想产生不同的随机数就需要用当前时间作为种子
即:
#!/usr/bin/python3
import random
import datetime
random.seed(datetime.datetime.now())
print ("Random number with当前时间: ", random.random())
输出结果:Random number with当前时间: 0.1915369729663604
#!/usr/bin/python3
import random
import datetime
random.seed(datetime.datetime.now())
print ("Random number with当前时间: ", random.random())
输出结果:Random number with当前时间: 0.26451817448470716
#!/usr/bin/python3
import random
import datetime
random.seed(datetime.datetime.now())
print ("Random number with当前时间: ", random.random())
输出结果:Random number with当前时间: 0.26258549654200924
#!/usr/bin/python3
import random
import datetime
random.seed(datetime.datetime.now())
print ("Random number with当前时间: ", random.random())
random.seed(datetime.datetime.now())
print ("Random number with当前时间: ", random.random())
random.seed(datetime.datetime.now())
print ("Random number with当前时间: ", random.random())
输出结果:结果相同
Random number with当前时间: 0.5998298461948733
Random number with当前时间: 0.5998298461948733
Random number with当前时间: 0.5998298461948733
总结:可以看出random.seed(datetime.datetime.now())每次输出的结果都不相同
只有在同时输出的结果才会相同,因为“同时”表明时间点是相同的