zoukankan      html  css  js  c++  java
  • time与datetime模块,random模块,os模块,sys模块,configparser模块,subprocess模块

    一、time与datetime模块

    ==========time模块==========

    1、时间有三种格式(*****)

    # 1、时间戳:秒数=>用于时间计算(得到的是浮点型,用于加减乘除运算)
    start=time.time()
    print(start,type(start)) #1596367382.30072 <class 'float'>
    
    # 2、格式化的字符串=>用于显示给人看(得到的是字符串类型,可用于写到文件中)
    res=time.strftime("%Y-%m-%d %H:%S:%M %p")
    res=time.strftime("%Y-%m-%d %X")
    print(res,type(res)) #2020-08-02 19:23:02 <class 'str'>
    
    # 3、结构化的时间=>获取时间的某一部分(以此可以按照当前的时间计算出另外一个时间)
    res = time.localtime()
    res1 = time.gmtime()
    #不同之处就是localtime按照东八区计时(中国时间),gmtime以国际标准计算时间,英国本初子午线划分
    print(res) #time.struct_time(tm_year=2020, tm_mon=8, tm_mday=2, tm_hour=19, tm_min=23, tm_sec=2, tm_wday=6, tm_yday=215, tm_isdst=0)
    print(res1) #time.struct_time(tm_year=2020, tm_mon=8, tm_mday=2, tm_hour=11, tm_min=23, tm_sec=2, tm_wday=6, tm_yday=215, tm_isdst=0)
    print(type(res)) #<class 'time.struct_time'>
    print(res.tm_year)#选出其中一个 这里选出的是年  #打印出 2020

    2、时间格式转换

    # 2.1 时间戳---》格式化的字符串
    struct_time=time.localtime(3333.3)  #time.localtime()不传值默认就是time.time()
    res=time.strftime("%Y-%m",struct_time)
    print(res) #1970-01
    
    # 2.2 格式化的字符串---》时间戳
    struct_time=time.strptime("2017-07-03 11:11:11","%Y-%m-%d %H:%M:%S")
    res=time.mktime(struct_time)
    print(res) #1499051471.0

    3、

    print(time.ctime(3333.3)) # Thu Jan  1 08:55:33 1970  #time.ctime()不传值默认就是time.time()
    print(time.asctime(time.localtime(3333.3))) #Thu Jan  1 08:55:33 1970

    4、time.sleep(3)  #括号内传秒

    ==========datetime模块==========

    import datetime
    
    res=datetime.datetime.now()
    print(res) #直接获取当前时间
    
    print(datetime.date.fromtimestamp(time.time())) #时间戳直接转成日期格式 2020-08-02
    print(datetime.datetime.fromtimestamp(time.time())) #2020-08-02 19:55:15.371285
    #举例:计算三天前/三天后
    res=datetime.datetime.now() + datetime.timedelta(days=3)
    res=datetime.datetime.now() + datetime.timedelta(days=-3)
    print(res)
    #当前时间
    res=datetime.datetime.now()
    print(res)
    #以当前时间为基准,把年/月/日等换掉
    new_res=res.replace(year=1999,month=9)
    print(new_res)
    -------------------------------------------------------------------------------------------------
    # print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
    #print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
    # print(datetime.datetime.now() )
    # print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
    # print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
    # print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
    # print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分
    
    
    # c_time  = datetime.datetime.now()
    # print(c_time.replace(minute=3,hour=2)) #时间替换

    二、random模块

    import random
    
    # print(random.random())
    # print(random.randint(1,3))
    
    # print(random.choice([1,'23',[4,5]]))
    # print(random.sample([1,'23',[4,5]],2))
    
    # print(random.uniform(1,3))
    
    # item=[1,3,5,7,9]
    # random.shuffle(item)
    # print(item)
    
    
    # 随机验证码
    # print(chr(65))
    # print(chr(90))
    
    def make_code(n=5):
        res = ''
        for i in range(n):
            s1 = str(random.randint(0, 9))
            s2 = chr(random.randint(65, 90))
            res += random.choice([s1, s2])
        return res
    
    print(make_code(4))

    三、os模块

     os.system没有返回值  res=os.system()#0代表命令运行正确,1代表命令运行错误

    # import os
    # print(os.listdir("."))
    
    # import os
    
    # cmd=input(r"""
    # Microsoft Windows [版本 10.0.17763.1339]
    # (c) 2018 Microsoft Corporation。保留所有权利。
    #
    # %s=====> """ %os.getcwd())
    # res=os.system(cmd)
    # print('='*100)
    # print(res)
    
    
    import os
    # print(__file__)
    # print(os.path.abspath(__file__))
    
    # res=os.path.split("D:/python全栈15期/day21/03 os模块.py")
    # print(res)
    
    # print(os.path.basename("D:/python全栈15期/day21/03 os模块.py"))
    # print(os.path.dirname("D:/python全栈15期/day21/03 os模块.py"))
    
    # print(os.path.exists("D:/python全栈15期/day21/"))
    # print(os.path.isabs("D:/python全栈15期/day21/"))
    # print(os.path.isabs("/python全栈15期/day21/"))
    
    # print(os.path.isabs("python全栈15期/day21/"))
    
    # print(os.path.join("a",'b','D:c','d.txt'))
    
    
    # print(os.path.dirname(os.path.dirname(__file__)))
    
    # res=os.path.join(
    #     __file__,
    #     "..",
    #     ".."
    # )
    #
    # print(os.path.normpath(res))
    
    
    print(os.path.getsize(__file__))
    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下为"
    ",Linux下为"
    "
    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的大小

    四、sys模块

     sys.path第一个 环境变量参照当前执行文件(在包里就是被调用者),跟当前所在的文件无关
    导入包就是在导init__.py,导入模块,出发init__.py的运行
    包的使用者,处理环境变量,调用包,被倒入的包/模块
    绝对导入(通用):以包的根目录为起始点,开始导入
    相对导入(简单,只能在包里用):.当前文件   ..上一级 ...上一级   但是不能超出包

    import sys
    
    # sys.path
    # print(sys.argv)
    
    # src_file = input("源文件路径:").strip()
    # dst_file = input("目标文件路径:").strip()
    # src_file = sys.argv[1]
    # dst_file = sys.argv[2]
    #
    # with open(r"%s" %src_file,mode='rb') as f1,open(r"%s" %dst_file,mode='wb') as f2:
    #     for line in f1:
    #         f2.write(line)

    打印进度条

    # import time
    # print("[#               ]",end='')
    # time.sleep(0.3)
    # print("
    [##              ]",end='')
    # time.sleep(0.3)
    # print("
    [###             ]",end='')
    # time.sleep(0.3)
    # print("
    [####            ]",end='')
    
    
    # print("[%-15s]" % "###",)
    # print("[%-15s]" % "####",)
    
    
    import time
    
    def progress(percent):
        if percent > 1:
            percent=1
        print("
    [%-50s] %d%%" % ("#"*int(50*percent),int(100 * percent)),end='')
    
    total_size = 1025
    recv_size = 0
    
    while recv_size < total_size:
        # 每次下载1024
        time.sleep(0.3)
        recv_size+=1024
    
        percent = recv_size / total_size
    
        progress(percent)

    五、configparser模块

    import subprocess
    
    # pwd ; sasdfasdf ;echo 123
    
    obj = subprocess.Popen("diasfdafr", shell=True,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE
                           )
    
    res1=obj.stdout.read()
    res2=obj.stderr.read()
    # print(res1.decode('gbk'))
    print(res2.decode('gbk'))

     六、suprocess模块

    import  subprocess
     2 
     3 '''
     4 sh-3.2# ls /Users/egon/Desktop |grep txt$
     5 mysql.txt
     6 tt.txt
     7 事物.txt
     8 '''
     9 
    10 res1=subprocess.Popen('ls /Users/jieli/Desktop',shell=True,stdout=subprocess.PIPE)
    11 res=subprocess.Popen('grep txt$',shell=True,stdin=res1.stdout,
    12                  stdout=subprocess.PIPE)
    13 
    14 print(res.stdout.read().decode('utf-8'))
    15 
    16 
    17 #等同于上面,但是上面的优势在于,一个数据流可以和另外一个数据流交互,可以通过爬虫得到结果然后交给grep
    18 res1=subprocess.Popen('ls /Users/jieli/Desktop |grep txt$',shell=True,stdout=subprocess.PIPE)
    19 print(res1.stdout.read().decode('utf-8'))
    20 
    21 
    22 #windows下:
    23 # dir | findstr 'test*'
    24 # dir | findstr 'txt$'
    25 import subprocess
    26 res1=subprocess.Popen(r'dir C:UsersAdministratorPycharmProjects	est函数备课',shell=True,stdout=subprocess.PIPE)
    27 res=subprocess.Popen('findstr test*',shell=True,stdin=res1.stdout,
    28                  stdout=subprocess.PIPE)
    29 
    30 print(res.stdout.read().decode('gbk')) #subprocess使用当前系统默认编码,得到结果为bytes类型,在windows下需要用gbk解码
  • 相关阅读:
    一句话解释各种虚拟币的用途
    php 网站301重定向设置代码实战案例
    seo网页加速技术,预加载 DNS Prefetching 详解
    AI赌神称霸德扑的秘密,刚刚被《科学》“曝光”了
    java实现 HTTP/HTTPS请求绕过证书检测代码实现
    pyspider源码解读--调度器scheduler.py
    pyspider操作千万级库,pyspider在对接量级较大库的策略
    尼克《人工智能简史》谈人工智能的历史、现实与未来
    CentOS7使用yum命令安装Java1.8
    php ci nginx 伪静态rewrite配置方法
  • 原文地址:https://www.cnblogs.com/guojieying/p/13405801.html
Copyright © 2011-2022 走看看