zoukankan      html  css  js  c++  java
  • 复习模块

    一、timedatetime

    import time

    时间戳(timestamp):通常来说,时间戳表示的是从19701100:00:00开始按秒计算的偏移量。

    print(time.time())  # 1528188733.8373

     

    格式化的时间字符串(Format String)

    print(time.strftime("%Y-%m-%d %X"))  # 2018-06-05 16:52:13

     

    结构化的时间(struct_time)struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时)

    print(time.localtime())  # time.struct_time(tm_year=2018, tm_mon=6, tm_mday=5, tm_hour=16, tm_min=52, tm_sec=13, tm_wday=1, tm_yday=156, tm_isdst=0)

    print(time.gmtime())  # time.struct_time(tm_year=2018, tm_mon=6, tm_mday=5, tm_hour=8, tm_min=52, tm_sec=13, tm_wday=1, tm_yday=156, tm_isdst=0)

     

    转换

    print(time.localtime(time.time()))

    print(time.gmtime(time.time()))

    print(time.mktime(time.localtime()))  # 1528189230.0

     

    print(time.strftime("%Y-%m-%d %X",time.gmtime()))  # 2018-06-05 09:00:30

    print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X'))

     

    如果没有参数,将会将time.localtime()作为参数传入。

    print(time.asctime())  # Tue Jun 5 17:02:46 2018

     

    如果参数未给或者为None的时候,将会默认time.time()为参数

    print(time.ctime())  # Tue Jun 5 17:03:04 2018

    print(time.ctime(time.time()))  # Tue Jun 5 17:03:27 2018

     

    time.sleep(2)

     

    import datetime

    时间加减

    print(datetime.datetime.now())  # 2018-06-05 17:08:50.554154

    print(datetime.date.fromtimestamp(time.time()))  # 2018-06-05

    print(datetime.datetime.now()+datetime.timedelta(3))  # 2018-06-08 17:08:50.554274

    print(datetime.datetime.now()+datetime.timedelta(-3))  # 2018-06-02 17:08:50.554300

    print(datetime.datetime.now() + datetime.timedelta(hours=3))  # 2018-06-05 20:08:50.554319

    print(datetime.datetime.now() + datetime.timedelta(minutes=30))  # 2018-06-05 17:38:50.554345

     

    时间替换

    c_time = datetime.datetime.now()

    print(c_time.replace(minute=3,hour=2)) #2018-06-05 02:03:53.562862

     

    . random模块

    import random

    print(random.random())  # 0.6314922538999044   大于0且小于1之间的小数

    print(random.randint(1,3))  # 3    大于等于1且小于等于3之间的整数

    print(random.randrange(1,3)) # 2    大于等于1且小于3之间的整数

    print(random.choice([1,'23',[4,5]]))  # 1或者23或者[4,5]

    print(random.sample([1,'23',[4,5]],2))  # 列表元素任意2个组合

    print(random.uniform(1,3))  # 大于1小于3的小数,如1.927109612082716

     

    item=[1,3,5,7,9]

    random.shuffle(item) # 打乱item的顺序,相当于"洗牌"

    print(item) # [3, 5, 1, 7, 9]

     

    生成随机验证码

    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))  # TXGIS35Q3

     

    . os模块(os模块是与操作系统交互的一个接口)

    import os

    os.getcwd() # 获取当前工作目录,即当前python脚本工作的目录路径

    os.chdir("dirname")  # 改变当前脚本工作目录;相当于shellcd

    os.curdir() # 返回当前目录: ('.')

    os.pardir() # 获取当前目录的父目录字符串名:('..')

    os.makedirs('dirname1/dirname2')  # 可生成多层递归目录

    os.removedirs('dirname1')  # 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推

    os.mkdir('dirname')  #  生成单级目录;相当于shellmkdir dirname

    os.rmdir('dirname')  # 删除单级空目录,若目录不为空则无法删除,报错;相当于shellrmdir 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.path.normcase('c:/windows\system32\')

     

    .sys模块

    import sys

    sys.argv           命令行参数List,第一个元素是程序本身路径

    sys.exit(n)        退出程序,正常退出时exit(0)

    sys.version        获取Python解释程序的版本信息

    sys.maxint         最大的Int

    sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

    sys.platform       返回操作系统平台名称

     

    进度条

    import sys

    import time

     

    def progress(percent,width=50):

       if percent>=1:

           percent=1

       show_str=('[%%-%ds}' %width)%(int(width*percent)*'#')

       print(' %s %d%%' % (show_str,int(100*percent)),file=sys.stdout,flush=True,end='')

     

    data_size=1025

    recv_size=0

    while recv_size<data_size:

       time.sleep(0.1)

       recv_size+=100

       percent=recv_size/data_size

       progress(percent,width=70)

     

    . shutil模块(高级的 文件、文件夹、压缩包 处理模块)

     

    . json & pickle模块

    无论数据是怎样创建的,只要满足json格式,就可以json.loads出来,不一定非要dumps的数据才能loads

    import json

    dic={'name':'alvin','age':23,'sex':'male'}

    print(type(dic))  # <class 'dict'>

    j=json.dumps(dic)

    print(type(j))  # <class 'str'>

    f=open('序列化对象','w')

    f.write(j)

    f.close()

     

    import json

    f=open('序列化对象')

    data=json.loads(f.read())

     

    import pickle

    dic={'name':'alvin','age':23,'sex':'male'}

    print(type(dic))  # <class 'dict'>

    j=pickle.dumps(dic)

    print(type(j))  # <class 'bytes'>

    f=open('序列化对象_pickle','wb')

    f.write(j)

    f.close()

     

    import pickle

    f=open('序列化对象_pickle','rb')

    data=pickle.loads(f.read())

    print(data['age'])

     

    . hashlib模块

    import hashlib

    m=hashlib.md5()

    m.update('hello'.encode('utf8'))

    print(m.hexdigest())  # 5d41402abc4b2a76b9719d911017c592

    m.update('alvin'.encode('utf8'))

    print(m.hexdigest())  # 92a7e713c30abbb0319fa07da2a5c4af

     

    m2=hashlib.md5()

    m2.update('helloalvin'.encode('utf8'))

    print(m2.hexdigest())  # 92a7e713c30abbb0319fa07da2a5c4af

     

  • 相关阅读:
    买房的贷款时间是否是越长越好?https://www.zhihu.com/question/20842791
    asp.net cookie and session
    leelazero and google colab
    download file by python in google colab
    physical processor, core, logical processor
    通过powershell操作eventlog
    openxml in sql server
    get the page name from url
    How to Execute Page_Load() in Page's Base Class?
    Difference between HttpContext.Request and Request
  • 原文地址:https://www.cnblogs.com/yangli0504/p/9141612.html
Copyright © 2011-2022 走看看