zoukankan      html  css  js  c++  java
  • Python内置模块之time、random、hashlib、OS、sys、UUID模块

                        Python常用模块

    1、time模块

     在Python中,通常有这三种方式来表示时间:时间戳、元组(struct_time)、格式化的时间字符串:


    (1)时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。

    (2)格式化的时间字符串(Format String): ‘1988-03-16’

    (3)元组(struct_time) :struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天等)

    import time
    
    print(time.time()) #时间戳 (给计算机看的)
    print(time.localtime()) #元组结构化时间(操作时间的)
    print(time.strftime('%Y %m %d %X')) #让人可以直观看出来的
    
    #time.gmtime()方法把时间戳变成结构化时间;
    print(time.gmtime(888888888))
    
    #time.mktime()方法把结构化时间转换成时间戳
    print(time.mktime(time.localtime()))
    print(time.localtime())
    print(time.mktime(time.localtime()))
    #-------------------------------------------------------------
    #time.strftime()方法把结构化时间转换成 字符串时间
    print(time.strftime('%Y %m %d %X',time.localtime()))
    #time.strptime()方法把字符串时间 转换 成 结构化时间 print(time.strptime("2017 04 26 14:16:24","%Y %m %d %X"))
    import requests,json,datetime
    current_date=datetime.datetime.now().strftime("%Y%m%d") #20190218
    url = 'http://api.goseek.cn/Tools/holiday?date='+current_date
    response=requests.get(url=url).text
    flag=json.loads(response).get('data')
    print(flag) #工作日对应结果为 0, 休息日对应结果为 1, 节假日对应的结果为 2;
    判断当前日期是否为 工作日/休息日/节假日

    2、random模块

    #返回0-1之间的小数
    print(random.random())
    #返回1-6区间的整数 print(random.randint(1,6))
    #返回列表里面的任意1个元素 print(random.choice([1,23]))
    #返回列表里面任意2个元素 (sample样本 ) print(random.sample([1,2,3,4],2))
    #返回1到3之间的小数 print(random.uniform(1,3))
    # 打乱次序 item=[1,3,5,7,9] # random.shuffle(item) print(item)

     使用random模块生成5位验证码:

     1 def v_code():
     2     code = ''
     3     for i in range(5):
     4        Number=random.randint(0,9)       #得到随机数字
     5        Str=chr(random.randint(65,90))   #得到assic变里的随机英文字母
     6        Add=random.choice([Number,Str])  #随机选择  数字 和英文字母
     7        code=''.join([code,str(Add)])    #循环拼接5次得到一个,5个随机字母和随机数字的验证码
     8     return code
     9 
    10 
    11 print(v_code())

    3、hashlib模块

    MD5就是把任意长度的数据,转换成一串 固定长度的的16进制字符串的一种摘要算法;(通常使用16进制的字符串表示)

    import hashlib
    
    m=hashlib.md5()                       #得到一个hashlib库里的md5对象
    m.update('张根'.encode('utf-8'))    #调用MD5对象的 加密方法
    m.update('张根'.encode('utf-8'))    #MD5支持反复迭代摘要算法 第二次调用update() 摘要的数据是张根张根
    print(m.hexdigest())                  #digest()方法查询MD5对象的 加密的结果 以hex十六进制的数字表示出来
    
    n=hashlib.md5("加盐".encode('utf-8')) #由于同样的数据 经过MD5摘要算法加密出来的数据是一样的,可以在实例化MD5对象时加盐来 增强加密的效果;
    n.update('张根'.encode('utf-8'))
    n.update('张根'.encode('utf-8'))
    print(n.hexdigest())                 #n.hexdigest()和(m.hexdigest()的MD5加密的数据一样,算法一样 所以结果一样,N加了盐结果就不一样了;

    4.OS和sys模块

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

    sys模块是和Python解释器交互的接口

    ''
    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.argv           命令行参数List,第一个元素是程序本身路径
    sys.exit(n)        退出程序,正常退出时exit(0)
    sys.version        获取Python解释程序的版本信息
    sys.maxint         最大的Int值
    sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
    sys.platform       返回操作系统平台名称

    5.UUID、唯一数字

    通用唯一识别码:(Universally Unique Identifier)的缩写;

    当前时间+UUID生成数据库中唯一索引,可通过最左前缀匹配,索引某时间段内产生的数据;

    UUID模块参考:
    https://www.cnblogs.com/wang-yc/articles/5667605.html
    
    
    生成唯一索引列:
    from datetime import *
    import uuid
    unique_index_field=(lambda :datetime.now().strftime("%Y-%m-%d-%H-%M-%S------")+str(uuid.uuid1()))()

    6.datetime模块

    a.逻辑判断

        def clean(self):
            if self.cleaned_data.get('startdate') and self.cleaned_data.get('enddate'):
                startdate=datetime.datetime.strptime(self.cleaned_data.get('startdate'), '%Y年%m月%d日%H时%M分%S秒')
                enddate = datetime.datetime.strptime(self.cleaned_data.get('enddate'), '%Y年%m月%d日%H时%M分%S秒')
                if enddate > startdate:
                    return self.cleaned_data
                else:raise forms.ValidationError('日期选择错误:完成日期必须大于开始日期')

    b.计算

    今天的n天后的日期。

    now = datetime.datetime.now()
    delta = datetime.timedelta(days=3)
    n_days = now + delta
    print n_days.strftime('%Y-%m-%d %H:%M:%S')

    两个日期相差多少天?

    d1 = datetime.datetime.strptime('2012-03-05 17:41:20', '%Y-%m-%d %H:%M:%S')
    d2 = datetime.datetime.strptime('2012-03-02 17:41:20', '%Y-%m-%d %H:%M:%S')
    delta = d1 - d2
    print delta.days
        def jin_du(self,row=None, is_header=None):
            if is_header:
                return
    
            startdate =time.mktime(datetime.datetime.strptime(row.startdate, '%Y年%m月%d日%H时%M分%S秒').timetuple())
            enddate =time.mktime(datetime.datetime.strptime(row.enddate ,'%Y年%m月%d日%H时%M分%S秒').timetuple())
    
            total=enddate-startdate
            remain=enddate-time.time()
            percent=remain/total*100
            a='<div class="p2"><progress max="100" value="%s"></progress></div>'%(percent)
            # print(percent)
            if percent<0:
                a='<div class="p2"><progress max="100" value="0"></progress>已超时</div>'
            return mark_safe(a)

    c.中文时间

    datetime.datetime.now().strftime('%Y{0}%m{1}%d{2}%H{3}%M{4}%S{5}').format('','','',"",'','')
  • 相关阅读:
    leetcode -- 4Sum
    leetcode -- 3Sum Closest
    leetcode -- 3Sum
    leetcode -- Longest Common Prefix
    leetcode -- Container With Most Water
    leetcode -- Palindrome Number
    rep stos 指令(Intel汇编)
    利用反汇编手段解析C语言函数
    C语言反汇编入门实例
    系统栈的工作原理
  • 原文地址:https://www.cnblogs.com/sss4/p/6769225.html
Copyright © 2011-2022 走看看