导入模块的方式
import module_name
from nodule_name import name1,name2…
from module_name import *
from module_name import func as domo_func
time模块
time模块是与时间相关的模块
time.sleep()
延迟执行的时间
1
2
3
4
5
|
import time print ( 'hello python world' ) time.sleep( 2.0 ) # 延迟执行2秒 print ( 'life is short,i use python' ) |
time.time()
秒时间戳
1
2
3
4
|
import time # 时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量 print (time.time()) |
time.localtime()
查看本地时间
1
2
3
|
import time print (time.localtime()) |
time.strftime()
自定义时间格式 接收以时间元组,并返回以字符串表示的当地时间,格式由参数format决定
1
2
3
|
import time print (time.strftime( '%Y-%m-%d %H:%M:%S' )) |
strfttime里面的常用格式化参数
参数 | 描述 |
---|---|
%Y | 本地完整的年份,例如2022 |
%y | 去掉世纪的年份,例如22 |
%M | 分钟数 |
%m | 月份 |
%d | 一个月的第几天 |
%H | 一天中的第几个小时 |
%S | 秒数 |
%A | 本地完整星期名称,例如Saturday |
%a | 本地简化星期名称,例如Sat |
%B | 本地完整月份名称,例如March |
%b | 本地简化月份名称,例如Mar |
%p | 显示本地时间是am还是pm |
%x | 本地相应日期,例如03/05/22 |
%X | 本地相应时间,例如18:32:07 |
%j | 一年中的第几天 |
datetime()
datetime也是与时间相关的模块但不是time中的模块,需要import导入一下
datetime.datetime.now()输出当前时间
1
2
3
|
import datetime print (datetime.datetime.now()) |
random模块
random模块是随机模块
random.random()
随机生成[0,1)的数
1
2
3
|
import random print (random.random()) |
random.randint()
随机生成整数
1
2
3
|
import random print (random.randint( 1 , 5 )) |
random.choice()
随机在序列中取元素
1
2
3
|
import random print (random.choice( '1234hello python world' )) |
random.shuffie()
1
2
3
4
5
6
|
import random li = [ 1 , 4 , 7 , 5 , 3 , 0 ] # 将传入的容器进行乱序,注意1:改变的是容器本身。注意2:容器不能是元组 random.shuffle(li) # 将列表元素随机排列 print (li) |
random.randrange()
随机取整数
1
2
3
|
import random print (random.randrange( 1 , 10 , 2 )) # 随机取1,3,5,7,9 |
random.sample()
随机取样
1
2
3
4
|
import random li = [ 1 , 4 , 6 , 5 , 18 , 2 , 9 , 7 ] print (random.sample(li, 3 )) # 随机从li列表中取三个元素 |