>>> import random
>>> list = list(range(1,11))
>>> list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 在序列中随机选择一个值
>>> random.choice(list)
6
>>> random.choice(list)
9
>>> random.choice(list)
6
# 获取指定数量的随机序列
>>> random.sample(list, 3)
[4, 3, 1]
>>> random.sample(list, 3)
[3, 5, 10]
# 将序列顺序随机打乱
>>> random.shuffle(list)
>>> list
[3, 10, 8, 5, 9, 1, 4, 6, 7, 2]
>>> random.shuffle(list)
>>> list
[2, 9, 3, 5, 1, 8, 10, 7, 6, 4]
# 生成指定范围内的随机整数
>>> random.randint(1, 10)
4
>>> random.randint(1, 10)
6
# 生成随机浮点数
>>> random.random()
0.5570934639454602
# 生成指定bit位数的随机数
>>> random.getrandbits(5)
13
>>> random.getrandbits(5)
28
datetime模块中的两个常量
>>> import datetime
>>> datetime.MAXYEAR
9999
>>> datetime.MINYEAR
1
datetime模块中的date类
>>> d = datetime.date.today()
# date类的三个属性
>>> d.year
2020
>>> d.month
1
>>> d.day
31
# date类的weekday()方法和isoweekday()方法
>>> d.weekday() # 返回的周一为0, 周日为6
4
>>> d.isoweekday() # 返回的周一为1, 周日为7
5
# 手动创建date实例
>>> b = datetime.date(1999, 1, 1)
>>> b.year
1999
>>> b.day
1
datetime模块中的time类
>>> t = datetime.time(8, 40, 32)
>>> t.hour
8
>>> t.minute
40
>>> t.second
32
datetime模块中的datetime类
>>> import datetime
#调用datetime类中的now()方法返回当前时间
>>> n = datetime.datetime.now()
>>> n.year
2020
>>> n.month
1
>>> n.day
31
>>> n.second
29
>>> n.microsecond
47371
#手动创建datetime实例
>>> t = datetime.datetime(1999, 1, 31, 12, 50, 44, 490000)
>>> import datetime
#将字符串转成datetime格式
>>> s = '2008-1-1'
>>> t = datetime.datetime.strptime(s, '%Y-%m-%d')
>>> t
datetime.datetime(2008, 1, 1, 0, 0)
#将datetime格式转成字符串
>>> n = datetime.datetime.now()
>>> n
datetime.datetime(2020, 1, 31, 20, 20, 16, 103946)
>>> txt = n.strftime('%Y/%m/%d')
>>> txt
'2020/01/31'
# ‘%w’占位符表示星期数(星期天为0,星期一为1,星期六为6)
>>> import datetime
>>> d = datetime.datetime(2008, 1, 1, 22, 40)
>>> birthday = datetime.datetime(2006, 1, 1, 22, 00)
# 计算两个时间的时间差
>>> diff = d - birthday
>>> diff
datetime.timedelta(days=730, seconds=2400)
>>> diff.days
730
>>> diff.seconds
2400
>>> diff.total_seconds()
63074400.0
# 计算某一时间加上或减去730天
>>> d + datetime.timedelta(days = 730)
datetime.datetime(2009, 12, 31, 22, 40)
>>> d - datetime.timedelta(days = 730)
datetime.datetime(2006, 1, 1, 22, 40)