二、系统的内置模块#

python系统内置很多实用模块

1. sys模块#

  • sys.argv 获得启动时的参数
  • sys.path 获取加载的环境
  • sys.exit()程序退出

2. time模块#

time模块和世间相关

time.time()获取当前时间戳,单位时秒,(相对于1970年的0点0时0分0秒)

1
2
3
import time
result = time.time() # 获取当前时间
print(result)

time.sleep(秒)阻断程序

1
2
3
4
5
6
import time

# print('程序开始')
# 睡眠3秒钟
time.sleep(3)
# print('程序结束')

3. datetime模块#

datetime获取日期

datetime.datetime.now().year datetime.datetime.now().month datetime.datetime.now().day

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import datetime
# 获取当前年
year = datetime.datetime.now().year
# 获取月
month = datetime.datetime.now().month
# 获取日期
day = datetime.datetime.now().day
print(year)
print(month)
print(day)

4. math模块#

math是数学相关的库

1
2
3
4
5
math.pow求幂
math.floor取下
math.ceil取上
round四舍五入
math.sin cos tan…
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import math
# 幂
print(math.pow(10, 2))
# 向下取整
print(math.floor(1.8234234234234))
# 向上取整
print(math.ceil(1.1234234234234))
# 四舍五入
print(round(1.6234234234234))

# sin  传入弧度值  pi 3.14 180度
print(math.sin(1.57))

5. random模块#

random主要用来产生随机数

1
2
3
4
5
random.randint(start,end)随机整数,[start,end]
random.random()随机浮点数, [0,1)
random.uniform(start,end)随机浮点数, [start,end]
random.choice([])随机数组,返回单个元素
random.choices([])随机数组,返回列表
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import random

# 随机整数
print(random.randint(10, 20))
# 随机小数 [0, 1)
print(random.random())
# 随机浮点类型数据
print(random.uniform(1.3, 8.5))

# 从列表中随机获取元素
l = [10,20,30]
print(random.choice(l))

# 随机返回列表 返回单个元素的列表
print(random.choices(l))