datatime 和random.seed()

 可以用来返回系统当前时间

In [2]: import datetime                                                               

In [3]: now_time = datetime.datetime.now()                                            

In [4]: print(now_time)                                                               
2018-12-06 11:59:27.903432

返回当天日期

In [7]: now_day = datetime.date.today()                                               

In [8]: print(now_day)                                                                
2018-12-06

 time模块,时间间隔

import time
def sleeptime(hou, minu, seco):
    return hou*3600+minu*60+seco
times = sleeptime(0, 0, 2)
while True:
    time.sleep(times)
    print('每隔两秒打印一次')


>>>每隔两秒打印一次
   每隔两秒打印一次
   每隔两秒打印一次
   每隔两秒打印一次
   每隔两秒打印一次
   每隔两秒打印一次

random.seed()

random.seed()是随机数种子,也就是为随机数提供算法,完全相同的种子产生的随机数列是相同的,

所以如果想产生不同的随机数就需要用当前时间作为种子

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.8444218515250481
Random number with seed 0 :  0.8444218515250481
Random number with seed 0 :  0.8444218515250481
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.8444218515250481
Random number with seed 0 :  0.13436424411240122
Random number with seed 0 :  0.9560342718892494

 

import random, datetime
random.seed(datetime.datetime.now())
print ("Random number with seed 0 : ", random.random())
random.seed(datetime.datetime.now())
print ("Random number with seed 0 : ", random.random())
random.seed(datetime.datetime.now())
print ("Random number with seed 0 : ", random.random())
#结果
Random number with seed 0 :  0.08829031965734957
Random number with seed 0 :  0.6561513780191366
Random number with seed 0 :  0.5129750211769749

可以看出random.seed(datetime.datetime.now())每次输出的结果都不相同

只有在同时输出的结果才会相同,因为“同时”表明时间点是相同的      

 

你可能感兴趣的:(python)