zoukankan      html  css  js  c++  java
  • Python入门day22——常用模块time、datatime、random、os、sys

    time模块
    #一:time
    import time
    
    # 时间分为三种格式:
    # 1、时间戳:从1970年到现在经过的秒数
    #     作用:用于时间间隔的计算
    
    print(time.time()) # 1585566290.2427917
    
    # 2、格式化时间:按照某种格式显示的时间:2020-03-30 11:11:11
    #    作用:用于展示时间
    
    print(time.strftime('%Y-%m-%d %H:%M:%S %p')) # 2020-03-30 19:04:50 PM
    print(time.strftime('%Y-%m-%d %X')) # 2020-03-30 19:04:50
    
    # 3、结构化的时间
    #    作用:用于单独获取时间的某一部分
    
    res=time.localtime() #
    print(res) # time.struct_time(tm_year=2020, tm_mon=3, tm_mday=30, tm_hour=19, tm_min=4, tm_sec=50, tm_wday=0, tm_yday=90, tm_isdst=0)
    print(res.tm_year) # 2020
    print(res.tm_yday) # 90
     
    #二:datetime
    import datetime
     
    print(datetime.datetime.now()) # 2020-03-30 19:04:50.244786
    print(datetime.datetime.now() + datetime.timedelta(days=3)) # 2020-04-02 19:04:50.244786
    print(datetime.datetime.now() + datetime.timedelta(weeks=1))# 2020-04-06 19:04:50.244786
    
    # 时间模块需要掌握的操作
    # 1、时间格式的转换
    # struct_time(结构化时间)->时间戳
    import time 
    s_time=time.localtime() 
    print(time.mktime(s_time)) # 1585566290.0
    
    # 时间戳->struct_time
    tp_time=time.time()
    print(time.localtime(tp_time)) # time.struct_time(tm_year=2020, tm_mon=3, tm_mday=30, tm_hour=19, tm_min=18, tm_sec=20, tm_wday=0, tm_yday=90, tm_isdst=0)
    
    # 补充:世界标准时间与本地时间
    print(time.localtime())
    print(time.gmtime()) # 世界标准时间,了解
    print(time.localtime(333333333))
    print(time.gmtime(333333333))
    
    # 结果相差8个小时
    time.struct_time(tm_year=2020, tm_mon=3, tm_mday=30, tm_hour=19, tm_min=18, tm_sec=44, tm_wday=0, tm_yday=90, tm_isdst=0)
    time.struct_time(tm_year=2020, tm_mon=3, tm_mday=30, tm_hour=11, tm_min=18, tm_sec=44, tm_wday=0, tm_yday=90, tm_isdst=0)
    time.struct_time(tm_year=1980, tm_mon=7, tm_mday=25, tm_hour=8, tm_min=35, tm_sec=33, tm_wday=4, tm_yday=207, tm_isdst=0)
    time.struct_time(tm_year=1980, tm_mon=7, tm_mday=25, tm_hour=0, tm_min=35, tm_sec=33, tm_wday=4, tm_yday=207, tm_isdst=0)
    
    # struct_time->格式化的字符串形式的时间
    s_time=time.localtime()
    print(time.strftime('%Y-%m-%d %H:%M:%S',s_time))# 2020-03-30 19:20:00
    print(time.strptime('1988-03-03 11:11:11','%Y-%m-%d %H:%M:%S')) # time.struct_time(tm_year=1988, tm_mon=3, tm_mday=3, tm_hour=11, tm_min=11, tm_sec=11, tm_wday=3, tm_yday=63, tm_isdst=-1)
    
    
    # !!!真正需要掌握的只有一条: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) # 573966671.0
    
    # format string<---struct_time<---timestamp
    res=time.strftime('%Y-%m-%d %X',time.localtime(timestamp))
    print(res) # 1988-03-10 11:11:11
    
    time.sleep(3)
    
    # 了解知识
    import time
    print(time.asctime()) #Mon Mar 30 19:23:17 2020
    
    import datetime
    print(datetime.datetime.now()) # 2020-03-30 19:23:17.537136
    print(datetime.datetime.utcnow()) # 2020-03-30 11:23:17.537136 世界
    print(datetime.datetime.fromtimestamp(333333))  # 1970-01-05 04:35:33 相当于time.strftime('%Y-%m-%d %X',time.localtime(333333))
    
    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) # [5, 3, 7, 1, 9]
    
    # 应用:随机验证码
    
    import random
    #
    res=''
    # for i in range(6):
    #     从26大写字母中随机取出一个=chr(random.randint(65,90))
    #     从10个数字中随机取出一个=str(random.randint(0,9))
    #
    #     随机字符=random.choice([从26大写字母中随机取出一个,从10个数字中随机取出一个])
    #     res+=随机字符
    
    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)) # WE3233
    
    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下为"	
    ",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的大小
    
    # 二:详细解析
    
    os.listdir 获取某一个文件夹下的子文件和文件名
    import os
    
    print(os.listdir(r'D:/项目/老男孩/week5day22'))     # 获取该文件夹下的文件名
    print(os.listdir(r'.'))                            # 获取当前文件夹下的文件名
    os.path.getsize 查看文件大小
    
    import os
    
    res = os.path.getsize(r'D:/项目/老男孩/week5day22
    un.py')
    print(res) # 2025
    
    os.system('dir E:\Python学习相关')     # 打印文件夹下的文件信息
    
    os.rename('old_name', 'new_name')       # 重命名文件夹/目录
    规定key与value必须都是 字符串
    
    import os
    print(os.environ)       # 返回值是字典
    os.environ['xxq'] = 'NB'
    print(os.environ)
    
    import os
    print(__file__)                     # D:/项目/老男孩/week5/day22/My/03 os模块.py
    print(os.path.abspath(__file__))    # D:项目老男孩week5day223 os模块.py
    
    # 文件相关
    
    import os
    print(__file__)                             #D:/项目/老男孩/week5/day22/03 os模块.py
    
    print(os.path.abspath(__file__))          	# D:/项目/老男孩/week5/day22/03 os模块.py
    print(os.path.split('/a/b/c/d.txt'))        # 会把路径和文件切分开:('/a/b/c', 'd.txt')
    print(os.path.split(__file__))              # 会把路径和文件切分开:('D:/项目/老男孩/week5/day22', '03 os模块.py')
    
    print(os.path.dirname(__file__))            # 获取当前文件所在的文件夹名称:D:/项目/老男孩/week5/day22
    print(os.path.basename(__file__))           # 获取当前文件名称:03 os模块.py
    
    print(os.path.isabs(r'a'))                  # 判断是否为绝对路径:False
    print(os.path.isabs(r'D:/项目'))    # 判断是否为绝对路径:True
    
    print(os.path.isfile(r'test.py'))           # 判断是否是文件:True
    print(os.path.isfile(r'aaa'))               # 判断是否是文件:False
    
    print(os.path.join('a','b','C:\','d','e'))     # 文件夹的拼接 a/bcd
    
    # 规定起始目录
    
    # 推荐使用这种
    BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # D:/项目/老男孩/week5
    
    不推荐使用
    # BASE_DIR = os.path.normpath(os.path.join(
    #     __file__,
    #     '.'
    # )
    #
    # )
    
    print(BASE_DIR)     # D:项目老男孩week5
    
    # 在Python3.5之后,推出了一个新模块pathlib
    
    from pathlib import Path
    res = Path(__file__).parent.parent
    print(res) # D:项目老男孩week5
    
    from pathlib import Path
    res = Path('/a/b/c') / 'd\e.txt'
    print(res)      # acde.txt
    
    print(res.resolve())    # 格式规范化,把 / 变成 :E:acde.txt
    
    sys模块
    # 一:解析
    sys.argv
    
    import sys
    
    # python3 run.py 1 2 3
    # sys.argv 获取的是解释器后的参数值
    print(sys.argv)
    文件拷贝的原始方法
    
    src_file = input('原文件路径:').strip()
    dst_file = input('新文件路径:').strip()
    
    with open(r'%s'%src_file, mode='rb') as read_f,
        open(r'%s'%dst_file, mode='wb') as write_f:
        for line in read_f:
            write_f.write(line)
            
    # 文件拷贝的新方法
    
    src_file = sys.argv[1]
    dst_file = sys.argv[2]
    
    with open(r'%s'%src_file, mode='rb') as read_f,
        open(r'%s'%dst_file, mode='wb') as write_f:
        for line in read_f:
            write_f.write(line)
            
    # 在run.py所在的文件夹下,按住shift,右键,选择“在此处打开cmd”,输入
    # 格式:python3.8 run.py 原文件路径 新文件路径
    # python3 run.py D:1.docx D:2.docx   #拷贝成功
    
    # 二:进度条
    
    # print('[%-50s]' %'#')
    # print('[%-50s]' % '##')
    # print('[%-50s]' % '###')
    
    # 输出:
    [#                                                 ]
    [##                                                ]
    [###                                               ]
    import time
    
    res = ''
    for i in range(50):
        res += '#'
        time.sleep(0.2)
        print('
     [%-50s]' % res, end='')
        
    # 输出:  [##################################################]
    
    #进阶打印进度条
    
    import time
    recv_size = 0
    total_size = 25600
    
    while recv_size < total_size:
        # 模拟网速
        time.sleep(0.2)
        # 下载了1024个字节的数据
        recv_size += 1024
        # 打印进度条
        # print(recv_size)
        percent = recv_size / total_size    # 1024 / 25600
        if percent > 1:
            percent = 1
        res = int(50 * percent) * '>'
        print('
     [%-50s] %d%%' % (res,percent*100), end='')
    
    # 再次进阶打印进度条
    
    import time
    
    def progress(percent):
        if percent > 1:
            percent = 1
        res = int(50 * percent) * '>'
        print('
     [%-50s] %d%%' % (res,percent*100), end='')
    
    recv_size = 0
    total_size = 25600
    
    while recv_size < total_size:
        time.sleep(0.2)
        recv_size += 1024
        percent = recv_size / total_size    # 1024 / 25600
        progress(percent)
    
  • 相关阅读:
    use paramiko to connect remote server and execute command
    protect golang source code
    adjust jedi vim to python2 and python3
    install vim plugin local file offline
    add swap file if you only have 1G RAM
    datatables hyperlink in td
    django rest framework custom json format
    【JAVA基础】网络编程
    【JAVA基础】多线程
    【JAVA基础】String类的概述和使用
  • 原文地址:https://www.cnblogs.com/yding/p/12600932.html
Copyright © 2011-2022 走看看