模块
time与datetime模块
获取当前时间戳
import time
localtime = time.localtime(time.time())
print "本地时间为 :", localtime
本地时间为 : time.struct_time(tm_year=2016, tm_mon=4, tm_mday=7, tm_hour=10, tm_min=3, tm_sec=27, tm_wday=3, tm_yday=98, tm_isdst=0)
获取格式化时间
import time
localtime = time.asctime( time.localtime(time.time()) )
print "本地时间为 :", localtime
本地时间为 : Thu Apr 7 10:05:21 2016
按照某种格式显示的时间 strftime=格式化时间后的格式
import time
print(time.strftime('%Y-%m-%d %X')) # 格式化的时间字符串 '2021-06-10 14:43:07'
print(time.strftime('%Y-%m-%d %H:%M:%S')) # 和上面效果一样
datetime===精简化以上步骤
快速在格式化基础上显示时间
print(dateme.datetime.now()+datetime.timedelta(days=3))#在现有时间加上时间3天
===============================================================================================================================================================================================
时间戳:从1970年到现在经过的秒数
#用于时间间隔的计算
print(time.time()) # 时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量 返回类型是float
一.时间格式的转换、
stuck_time ---> 时间戳
import time
s_time = time.localtime()
print(time.mktime(s_time))#秒数:1623316665.0
2.时间戳--->stuct_time
import time
tp_time=time.time()
print(time.localtime(tp_time))
#time.struct_time(tm_year=2021, tm_mon=6, tm_mday=10, tm_hour=17, tm_min=17, tm_sec=24, tm_wday=3, tm_yday=161, tm_isdst=0)
3.struct_time---->格式化时间字符串
import time
s_time=time.localtime()
print(time.strftime_time('%Y-%m-%d %H:%M:%S%Y',s_time))
# print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X')) # 把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作
print(time.localtime()) # 本地时区的struct_time
print(time.gmtime()) # UTC时区的struct_time
真正掌握:format strings'格式化字符串的时间'再到struct_time 再到timestamp'时间戳'互相转换
import time
struck_time =time.strptime(str,fmt='1998-03-03 11:11:11','%Y-%m-%d %H:%M:%S%Y')
timestamp =time.mktime(struct_time)+7*86400
print(res)
# 在这个函数中,format默认为:"%a %b %d %H:%M:%S %Y"
random 模块
import random
print(random.random()) # 0~1之间的随机小数
print(random.randint(1,3)) # 大于等于1且小于等于3的整数
print(random.randrange(1,3)) # 大于等于1且小于3的整数
print(random.sample([1,'23',[4, 5]], n)) #列表元素任n个组合 n代表个数
print(random.uniform(1,3)) #大于1小于3 的小数
item =[1,3,5,7,9]
random.shuffle(item)
print(item)# 打乱列表里的顺序,相当于洗牌
import random
a = ['ahh','hhh','zzz','emm']
print(random.sample(a,3)) # ['hhh', 'zzz', 'ahh']
print(random.choice('seq')) # 从集群population中选取k个元素,返回一个列表,集群可以是list、tuple、str、set
从非空序列中随机选取一个数据并带回,该序列可以是list、tuple、str、set。如果序列为空,则弹出IndexError错误
print(random.choices(population, weights=None, *, cum_weights=None, k=1)) # python 3.6新增版本
population:集群 weights:相对权重 cum_weights:累加权重 k:选取次数
例:
a = [8, 2, 6, 4, 9]
# 1 随机
print(random.choices(a, k=5))
# 2 对应变量a输出的结果始终为 [6, 6, 6, 6, 6],输出全是中间成员6
print(random.choices(a, weights=[0, 0, 1, 0, 0], k=5))
# 3 随机
print(random.choices(a, weights=[1, 1, 1, 1, 1], k=5))
# 4 对应变量a输出的结果始终为 [8, 8, 8, 8, 8],输出全是第一个成员8
print(random.choices(a, cum_weights=[2, 2, 2, 2, 2], k=5))
random.shuffle(lst)
随机打乱序列lst的顺序并重新排序,注意它无返回值,
另外lst只能是一个可变序列,且只支持有下标的序列,因此它也不适用于set,你最好只把它用在列表上
# 随机验证码:
import random
def make_code(n):
res=''
for i in range(n):
s1=chr(random.randint(65,90))
s2=str(random.randint(0,9))
res+=random.choice([s1,s2])
return res
print(make_code(9))-
os模块
import os
os.getcwd() # 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname") # 改变当前脚本工作目录;相当于shell下cd
os.curdir # 返回当前目录: ('.')
os.pardir # 获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2') # 可生成多层递归目录
os.removedirs('dirname1') # 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname') # 生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname') # 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
***os.listdir('dirname') # 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() # 删除一个文件
os.rename("oldname", "newname") # 重命名文件/目录
os.stat('path/filename') # 获取文件/目录信息
os.sep # 输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"
os.linesep # 输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
os.pathsep # 输出用于分割文件路径的字符串 win下为;,Linux下为:
os.name # 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
***os.system("bash command") # 运行shell命令,直接显示
os.environ # 获取系统环境变量
os.path.abspath(path) # 返回path规范化的绝对路径
os.path.split(path) # 将path分割成目录和文件名二元组返回
os.path.dirname(path) # 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) # 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) # 如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path) # 如果path是绝对路径,返回True
os.path.isfile(path) # 如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path) # 如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]]) # 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path) # 返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) # 返回path所指向的文件或者目录的最后修改时间
os.path.getsize(path) # 返回path的大小
os路径处理
import os, sys
possible_topdir = os.path.normpath(os.path.join(
os.path.abspath(file),
os.pardir, # 上一级
os.pardir,
os.pardir
))
sys.path.insert(0, possible_topdir)
import subprocess
import time
obj = subprocess.Popen('tasklist',shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# print('hello')
# time.sleep(3)
res1 = obj.stdout.read()
res2 = obj.stderr.read()
print(res1.decode('gbk'))
print(res2)

浙公网安备 33010602011771号