time,random ,os,sys模块
time
时间分为三种格式:
1、时间戳:从1970年到现在经过的秒数
作用:用于时间间隔的计算
import time print(time.time())
2、按照某种格式显示的时间:2020-03-30 11:11:11
作用:用于展示时间
print(time.strftime('%Y-%m-%d %H:%M:%S %p')) print(time.strftime('%Y-%m-%d %X'))
3、结构化的时间
作用:用于单独获取时间的某一部分
res=time.localtime() print(res) print(res.tm_year) print(res.tm_yday)
datatime
import datetime print(datetime.datetime.now()) print(datetime.datetime.now() + datetime.timedelta(days=3)) print(datetime.datetime.now() + datetime.timedelta(weeks=1))
1、时间格式的转换
# struct_time->时间戳 import time s_time=time.localtime() print(time.mktime(s_time)) # 时间戳->struct_time tp_time=time.time() print(time.localtime(tp_time)) # 补充:世界标准时间与本地时间 print(time.localtime()) print(time.gmtime()) # 世界标准时间,了解 print(time.localtime(333333333)) print(time.gmtime(333333333)) # struct_time->格式化的字符串形式的时间 s_time=time.localtime() print(time.strftime('%Y-%m-%d %H:%M:%S',s_time)) print(time.strptime('1988-03-03 11:11:11','%Y-%m-%d %H:%M:%S'))
format string<------>timestamp '1988-03-03 11:11:11'+7 format string--->struct_time--->timestamp struct_time=time.strptime('1988-03-03 11:11:11','%Y-%m-%d %H:%M:%S') timestamp=time.mktime(struct_time)+7*86400 print(timestamp) format string<---struct_time<---timestamp res=time.strftime('%Y-%m-%d %X',time.localtime(timestamp)) print(res) time.sleep(3)
import datetime print(datetime.datetime.now()) print(datetime.datetime.utcnow()) print(datetime.datetime.fromtimestamp(333333))
#进度条 import time res='' for i in range(50): res+='#' time.sleep(0.5) print('\r[%-50s]' % res,end='')
random
import random
print(random.random()) #(0,1)----float 大于0且小于1之间的小数
print(random.randint(1, 3)) # [1,3] 大于等于1且小于等于3之间的整数
print(random.randrange(1, 3)) # [1,3) 大于等于1且小于3之间的整数
print(random.choice([111, 'aaa', [4, 5]])) # 1或者23或者[4,5]
print(random.sample([111, 'aaa', 'ccc','ddd'],2)) # 列表元素任意2个组合
print(random.uniform(1, 3)) # 大于1小于3的小数,如1.927109612082716
item = [1, 3, 5, 7, 9]
random.shuffle(item) # 打乱item的顺序,相当于"洗牌"
print(item)
# 应用:随机验证码
import random
def make_code(size=4):
res=''
for i in range(size):
s1=chr(random.randint(65,90))
s2=str(random.randint(0,9))
res+=random.choice([s1,s2])
return res
print(make_code(6))
os
# 获取某一个文件夹下所有的子文件以及子文件夹的名字
res=os.listdir('.')
print(res)
os.remove("newname") 删除一个文件
os.rename("oldname","newname") 重命名文件/目录
os.environ()# 规定:key与value必须都为字符串
os.environ['aaaaaaaaaa']='111'
print(os.environ)
print(os.path.dirname(r'/a/b/c/d.txt'))
print(os.path.basename(r'/a/b/c/d.txt'))
print(os.path.isfile(r'笔记.txt'))
print(os.path.isfile(r'aaa'))
print(os.path.isdir(r'aaa'))
print(os.path.join('a','/','b','c','d'))
sys
import time
def progress(percent):
if percent > 1:
percent = 1
res = int(50 * percent) * '#'
print('\r[%-50s] %d%%' % (res, int(100 * percent)), end='')
recv_size = 0
total_size = 1025011
while recv_size < total_size:
time.sleep(0.01)
recv_size += 1024
# 打印进度条
# print(recv_size)
percent = recv_size / total_size
progress(percent)