python时间模块,,import tim


import time
import datetime
print(time.altzone/3600) 返回以秒为单位的UTC时间
print(time.asctime()) 返回日期
t=time.localtime() 返回时间对象
print(t.tm_year,t.tm_mday)

t.tm_year:返回年份

t.tm_mday:当月开始到当天的天数
print(time.time()+3600*3)从1970年以秒为单位再加3个小时
print(time.time())
print(time.strptime("2017-1-5 15:35","%Y-%m-%d %H:%M"))#转换成时间对象
t2=time.strptime("2017-1-5 15:35","%Y-%m-%d %H:%M")
print(time.mktime(t2))将时间对象转换为时间戳
t3=time.localtime(time.mktime(t2))将时间戳转换为时间对象
t3_str=time.strftime("%Y-%m-%d-%H-%M.log",t3)将时间对象转换为字符串
print(t3_str)
print(datetime.datetime.now()) 返回当前时间
print(datetime.datetime.fromtimestamp(time.time()-3600)) 将当前时间减去一个小时
print(datetime.datetime.now()+datetime.timedelta(days=3)) 当前时间加3天

random模块

print(random.random())

随机打印一个0点几的小数

print(random.randint(1,2))

随机取1到2的整数,包括1和2

print(random.randrange(1,5))

随机取1到5,不包括5

random.sample(range(100),5)

在100个整数内随机取5个数字,组成列表

random.sample(‘abcde’,2)

随机取2个字符

string模块

print(string.ascii_letters+string.digits)将ascii码字符大小写和0到9数字组合在一起

print(random.sample(str_source,6))在上面的字符中随机取6个字符组成列表

print(‘’,join(random.sample(string.ascii_letters+string.digits,6))

随机取6个字符,并且去掉连接符组合在一起

随机生成4位随机数

checkcode=‘‘

for i in range(4):
current=random.randrange(0,4)
if current != i:
temp=chr(random.randint(65,90))
else:
temp=random.randint(0,9)
checkcode+=str(temp)
print(checkcode)

shutil模块

shutil.copyfileobj(f1,f2)将f1文件的内容复制到f2文件中

shutil.copy(r"E:\workspace\s14\day1\sys.py","test")

将sys.py这个文件复制到当前路径下,改名为test

shutil.copytree(r"E:\workspace\s14\day1","day1_new")

把源目录拷贝到当前目录下

shutil.make_archive(r"c;\day1",format="zip",root_dir=r"E:\workspace\s14\day1")

把目录压缩到C盘下,取名为day1,格式为zip的压缩包

import zipfile
zip_obj=zipfile.ZipFile(r"c;\day1_new","w")
zip_obj.write("test1")
zip_obj.close()

上面是将day1_new这个压缩包打开,覆盖模式,将test1文件添加进去

import tarfile
tar=tarfile.open(r‘c;\day1_new‘,‘w‘)
tar.add(r"c;\day1.zip")
tar.close()

上面是将day1.zip的压缩包添加到day1_new压缩包当中去

python时间模块

评论关闭