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") #
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位验证码:

 def v_code():
code = ''
for i in range(5):
Number=random.randint(0,9) #得到随机数字
Str=chr(random.randint(65,90)) #得到assic变里的随机英文字母
Add=random.choice([Number,Str]) #随机选择 数字 和英文字母
code=''.join([code,str(Add)]) #循环拼接5次得到一个,5个随机字母和随机数字的验证码
return code 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下为"\t\n",Linux下为"\n"
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('年','月','日',"时",'分','秒')

Python内置模块之time、random、hashlib、OS、sys、UUID模块的更多相关文章

  1. python之模块random,time,os,sys,序列化模块(json,pickle),collection

    引入:什么是模块:   一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类型. 1.使用python编写的代码(.py ...

  2. python time,random,os,sys,序列化模块

    一.time模块 表示时间的三种方式 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的时间字符串: (1)时间戳(timestamp) :通常来说,时间戳 ...

  3. time,random,os,sys,序列化模块

    一.time模块 表示时间的三种方式 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的时间字符串: (1)时间戳(timestamp) :通常来说,时间戳 ...

  4. 常用模块random,time,os,sys,序列化模块

    一丶random模块 取随机数的模块 #导入random模块 import random #取随机小数: r = random.random() #取大于零且小于一之间的小数 print(r) #0. ...

  5. 模块 - random/string/os/sys/shutil/zipfile/tarfile

    random 模块 方法: >>> random.randint(1,3) #会包含 1 2 3 3 >>> random.randrange(1,3) #会包含 ...

  6. time/datetime/random/string/os/sys/shutil/zipfile/tarfile - 总结

    time 模块: time.time() #时间戳 time.localtime() #当前时间对象元组 time.localtime(123123) #根据时间戳的时间对象 time.mktime( ...

  7. collection,random,os,sys,序列化模块

    一.collection 模块 python拥有一些内置的数据类型,比如 str,list.tuple.dict.set等 collection模块在这些内置的数据类型的基础上,提供了额外的数据类型: ...

  8. Python常用模块os & sys & shutil模块

    OS模块 import os ''' os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作目录: ...

  9. random、os、时间模块

    一.random 模块 1.随机小数 random.random()   #产生大于0且小于1之间的小数 random.uniform(1,3)   #产生1到3之间的随机小数 2.随机整数 rand ...

  10. OS&SYS&Shuti模块

    #sys.argv   主要针对脚本可以读取参数 Shuti模块 import shutil f1=open('笔记',encoding='utf-8') f2=open('笔记2','w',enco ...

随机推荐

  1. ZOJ 3987 Numbers(Java枚举)

    http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3987 题意:给出一个数n,现在要将它分为m个数,这m个数相加起来必须等于n ...

  2. HttpDns原理

    什么是 DNS DNS(Domain Name System,域名系统),DNS 服务用于在网络请求时,将域名转为 IP 地址.能够使用户更方便的访问互联网,而不用去记住能够被机器直接读取的 IP 数 ...

  3. SyncDictionary

    using System; using System.Collections; using System.Collections.Generic; using System.Threading; us ...

  4. C#在高分屏上让窗体程序忽略系统的显示缩放

    [STAThread] static void Main() { ) SetProcessDPIAware(); Application.EnableVisualStyles(); Applicati ...

  5. virtualbox中的虚拟机和windows共享文件夹

    http://www.jianshu.com/p/4e3c8b06cb06 为什么要共享文件夹? 在工作的过程当中会使用到不同的软件开发环境,php的,python的,nodejs的为了隔离这些应用环 ...

  6. Qt的QVariant类

    QStandardItemModel类中的函数 bool setData(const QModelIndex &index, const QVariant &value, int ro ...

  7. JS添加/移除事件

    事件的传播方式 <div id="father"> <div id="son"></div> </div> &l ...

  8. Mac 如何安装 chromedriver

    1.使用brew  命令 前提是要安装 brew 这里不做介绍 使用命令 brew install chromedriver 如上图出现错误,根据提示可以使用如下命令安装 brew cask inst ...

  9. Python 闭包(Closure)

    Python  闭包 (Closure) 这里介绍一下python 的闭包 基本概念 闭包(closure)是函数式编程的重要的语法结构. 函数式编程的一个特点就是,允许把函数本身作为参数传入另一个函 ...

  10. SublimeText3按ctrl+b执行python无反应

    现象:在Sublime中打开.py文件,按”ctrl+b”执行时无反应.点击工具->编译系统中已经有且识别到Python,但执行”run(ctrl+shift+b)”时无反应,Sublime左下 ...