数学模块 math库
import math
常用函数:
# math.ceil() 向上取整, 内置函数 round() 四舍五入
res = math.ceil(2.25) #(输出) 3
# math.floor() 向下取整
res = math.floor(2.55) #(输出) 2
# math.pow() 计算数值的n次方, 结果是浮点
res = math.pow(2, 3) #(输出) 8.0
# math.sqrt() 开平方运算, 结果是浮点
res = math.sqrt(4) #(输出) 2.0
# math.fabs() 计算绝对值, 结果是浮点
res = math.fabs(-3) #(输出) 3.0
# math.modf() 把一个数值拆分成小数和整数组成的元组
res = math.modf(3.14) #(输出) (0.14000000000000012, 3.0)
# math.copysign(x, y) 把y的正负符号拷贝给x, 并返回x, 结果为浮点
res = math.copysign(3.14, -13) #(输出) -3.14
# math.fsum(iterable) 将一个容器类型数据中的元素进行一个求和运算, 结果为浮点
res = math.fsum([1,2,3]) #(输出) 6.0
# math.factorial 阶乘, 结果为整数
res = math.factorial(3) #(输出) 6
# math提供的常量
print(math.pi) #(输出) 3.141592653589793
随机模块 random
import random
常用函数:
# random.random() 返回 [0.0 - 1.0) 之间的随机小数(左闭右开)
res = random.random() #(输出) 0.26995258727388705
# random.randrange([start], end, [步进值]) 随机获取指定范围内 [start, end) 的整数, start不写默认为0
# 随机数的应用场景: 数字验证码, 高并发下的订单号
res = random.randrange(5) #(输出) 4
# random.randint() 随机产生指定范围内的随机整数(左右都取的到)
res = random.randint(5,10) #(输出) 8
# random.uniform() 获取指定范围内的随机小数(左闭右开)
res = random.uniform(5,10) #(输出) 5.7405118148754335
# random.choice() 随机获取容器类型中的值
res = random.choice('123') #(输出) 3
res = random.choice([1,2,3]) #(输出) 2
# random.shuffle() 随机打乱当前列表中的值
varlist = [1,2,3,4,5,6]
random.shuffle(varlist)
print(varlist) #(输出) [3, 4, 2, 5, 1, 6]
时间模块 time
import time
专业名词:
时间戳:表示从1970年1月1日0时0分0秒到现在的一个秒数, 目前可以计算到2038年
time()
res = time.time()
print(res) #(输出) 1592362262.516115
时间字符串:Wed Jun 17 10:51:02 2020
ctime()
res = time.ctime()
print(res) #(输出) Wed Jun 17 10:51:02 2020
时间元组:time.struct_time(tm_year=2020, tm_mon=6, tm_mday=17, tm_hour=10, tm_min=56, tm_sec=58, tm_wday=2, tm_yday=169, tm_isdst=0)
# 获取当前系统时间, 返回时间元组
res = time.localtime()
print(res) #(输出) time.struct_time(tm_year=2020, tm_mon=6, tm_mday=25, tm_hour=19, tm_min=33, tm_sec=59, tm_wday=3, tm_yday=177, tm_isdst=0)
时间元组存在如下值:
(表格来自官方文档)请注意,与C结构不同,月份值是 [1,12] 的范围,而不是 [0,11]
t = 1592362618.182501
res = time.localtime(t) # 通过时间戳获取时间元组
# 使用localtime方法获取的时间元组, 如何格式化为 xxxx年xx月xx日 时: 分: 秒 星期几
print(f'{res.tm_year}年{res.tm_mon}月{res.tm_mday}日 {res.tm_hour}: {res.tm_min}: {res.tm_sec} 星期{res.tm_wday+1}')
#(输出) 2020年6月17日 10: 56: 58 星期3
下面是格式化方式
time.strftime() 格式化时间
t = 1592362618.182501
res = time.localtime(t) # res里存放了时间元组
# 年-月-日 时: 分: 秒 星期几
res = time.strftime('%Y-%m-%d %H:%M:%S %w')
print(res) #(输出) 2020-06-17 12:28:42 3
time.sleep(t) 暂停当前线程t秒
time.perf_counter 获得当前程序的执行时间,用作计算程序执行耗时
start = time.perf_counter()
for i in range(1000000):
if 'abc' > 'acd':
pass
end = time.perf_counter()
print(end-start)
日历模块 calender
import calendar
mothrange(年,月)
返回指定年份和月份的数据,月份的第一天是周几,和月份中的天数
res = calendar.monthrange(2020, 4)
print(res)
#(输出) (2, 30)