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") #
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模块的更多相关文章
- python之模块random,time,os,sys,序列化模块(json,pickle),collection
引入:什么是模块: 一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类型. 1.使用python编写的代码(.py ...
- python time,random,os,sys,序列化模块
一.time模块 表示时间的三种方式 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的时间字符串: (1)时间戳(timestamp) :通常来说,时间戳 ...
- time,random,os,sys,序列化模块
一.time模块 表示时间的三种方式 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的时间字符串: (1)时间戳(timestamp) :通常来说,时间戳 ...
- 常用模块random,time,os,sys,序列化模块
一丶random模块 取随机数的模块 #导入random模块 import random #取随机小数: r = random.random() #取大于零且小于一之间的小数 print(r) #0. ...
- 模块 - random/string/os/sys/shutil/zipfile/tarfile
random 模块 方法: >>> random.randint(1,3) #会包含 1 2 3 3 >>> random.randrange(1,3) #会包含 ...
- time/datetime/random/string/os/sys/shutil/zipfile/tarfile - 总结
time 模块: time.time() #时间戳 time.localtime() #当前时间对象元组 time.localtime(123123) #根据时间戳的时间对象 time.mktime( ...
- collection,random,os,sys,序列化模块
一.collection 模块 python拥有一些内置的数据类型,比如 str,list.tuple.dict.set等 collection模块在这些内置的数据类型的基础上,提供了额外的数据类型: ...
- Python常用模块os & sys & shutil模块
OS模块 import os ''' os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作目录: ...
- random、os、时间模块
一.random 模块 1.随机小数 random.random() #产生大于0且小于1之间的小数 random.uniform(1,3) #产生1到3之间的随机小数 2.随机整数 rand ...
- OS&SYS&Shuti模块
#sys.argv 主要针对脚本可以读取参数 Shuti模块 import shutil f1=open('笔记',encoding='utf-8') f2=open('笔记2','w',enco ...
随机推荐
- React native中的组建通知通信:
有这么一个需求,在B页面pop()回到A页面,需要A页面执行刷新,那么我们可以采用以下方法: 1:在A页面Push到B页面中,加上一个A页面中的刷新函数做为参数,然后在B页面中在pop()函数封装后通 ...
- P3146 [USACO16OPEN]248 & P3147 [USACO16OPEN]262144
注:两道题目题意是一样的,但是数据范围不同,一个为弱化版,另一个为强化版. P3146传送门(弱化版) 思路: 区间动规,设 f [ i ][ j ] 表示在区间 i ~ j 中获得的最大值,与普通区 ...
- python 排序 由大到小
import functools class Solution: # @param {integer[]} nums # @return {string} def largestNumber(self ...
- [原][源码][tinyxml][opencv]按照规格剪切所有的图片
源码: #include <iostream> #include <fstream> #include <opencv2/core/core.hpp> #inclu ...
- new int
new int, 在申请内存,定义int变量:new int (100),在申请内存,定义int变量,并初始化为100:new int[100] , 在申请内存,定义int数组变量.
- Java 8里面lambda的最佳实践
Java 8已经推出一段时间了,越来越多开发人员选择升级JDK,这条热门动弹里面看出,JDK7最多,其次是6和8,这是好事! 在8 里面Lambda是最火的主题,不仅仅是因为语法的改变,更重要的是带来 ...
- QT---事件系统
1 QT事件系统 1.1 事件的定义 QT中事件是有专门的类QEvent,常见的有键盘事件QKeyEvent.鼠标事件QMouseEvent和定时器事件QTimerEvent.例如用 ...
- 清理SuperMap iclient 三维插件的缓存批处理
在windows任何位置,新建一个文本文件,将下面内容复制到文本文件中并保存,然后修改该文本文件后缀为.bat,鼠标点击执行即可完成清理工作~ @echo off title 清理三维缓存 @echo ...
- 解决微信video全屏的问题,不在本页面播放
在微信浏览器中使用video标签,点击播放会跳出本页面,自动进行全屏播放,原因是自动跳转到手机微信内置的浏览器中去播放去了!!! 在video中加上连个属性就好了,反正最近的一个项目,我是这样做的就好 ...
- every day a practice —— morning(6)
"Nearly one in five job ads for China's 2018 national civil service called for 'men only' or 'm ...