Python3内置模块详解1

转自:http://blog.51cto.com/egon09/1840425

一:内建模块

  1. time和datetime(http://www.jb51.net/article/49326.htm)


在Python中,通常有这几种方式来表示时间:1)时间戳 2)格式化的时间字符串 3)元组(struct_time)共九个元素。由于Python的time模块实现主要调用C库,所以各个平台可能有所不同。


UTC(Coordinated Universal Time,世界协调时)亦即格林威治天文时间,世界标准时间。在中国为UTC+8。DST(Daylight Saving Time)即夏令时。


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


元组(struct_time)方式:struct_time元组共有9个元素,返回struct_time的函数主要有gmtime(),localtime(),strptime()。下面列出这种方式元组中的几个元素:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#_*_coding:utf-8_*_
import  time
 
 
# print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
# print(time.altzone)  #返回与utc时间的时间差,以秒计算\
# print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016",
# print(time.localtime()) #返回本地时间 的struct time对象格式
# print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式
 
# print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016",
#print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上
 
 
 
# 日期字符串 转成  时间戳
# string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
# print(string_2_struct)
# #
# struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳
# print(struct_2_stamp)
 
 
 
#将时间戳转为字符串格式
# print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
# print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式
 
#时间加减
import  datetime
 
# print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
#print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
# print(datetime.datetime.now() )
# print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
# print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
# print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
# print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分
 
 
#
# c_time  = datetime.datetime.now()
# print(c_time.replace(minute=3,hour=2)) #时间替换

格式参照

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
% a    本地(locale)简化星期名称    
% A    本地完整星期名称    
% b    本地简化月份名称    
% B    本地完整月份名称    
% c    本地相应的日期和时间表示    
% d    一个月中的第几天( 01  -  31 )    
% H    一天中的第几个小时( 24 小时制, 00  -  23 )    
% I    第几个小时( 12 小时制, 01  -  12 )    
% j    一年中的第几天( 001  -  366 )    
% m    月份( 01  -  12 )    
% M    分钟数( 00  -  59 )    
% p    本地am或者pm的相应符    一    
% S    秒( 01  -  61 )    二    
% U    一年中的星期数。( 00  -  53 星期天是一个星期的开始。)第一个星期天之前的所有天数都放在第 0 周。    三    
% w    一个星期中的第几天( 0  -  6 0 是星期天)    三    
% W    和 % U基本相同,不同的是 % W以星期一为一个星期的开始。    
% x    本地相应日期    
% X    本地相应时间    
% y    去掉世纪的年份( 00  -  99 )    
% Y    完整的年份    
% Z    时区的名字(如果不存在为空字符)    
% %     % ’字符

 时间关系转换

wKioL1e28cPBlYGaAAGLKN2Vq_c463.jpg-wh_50


更多点击这里

2.random模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env python
#_*_encoding: utf-8_*_
import  random
print  (random.random())   #0.6445010863311293  
#random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0
print  (random.randint( 1 , 7 ))  #4
#random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。
# 其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b
print  (random.randrange( 1 , 10 ))  #5
#random.randrange的函数原型为:random.randrange([start], stop[, step]),
# 从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),
# 结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。
# random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。
print (random.choice( 'liukuni' ))  #i
#random.choice从序列中获取一个随机元素。
# 其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。
# 这里要说明一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。
# list, tuple, 字符串都属于sequence。有关sequence可以查看python手册数据模型这一章。
# 下面是使用choice的一些例子:
print (random.choice( "学习Python" )) #学
print (random.choice([ "JGood" , "is" , "a" , "handsome" , "boy" ]))   #List
print (random.choice(( "Tuple" , "List" , "Dict" )))    #List
print (random.sample([ 1 , 2 , 3 , 4 , 5 ], 3 ))     #[1, 2, 5]
#random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。


实际应用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/env python
# encoding: utf-8
import  random
import  string
#随机整数:
print ( random.randint( 0 , 99 ))   #70
 
#随机选取0到100间的偶数:
print (random.randrange( 0 101 2 ))  #4
 
#随机浮点数:
print ( random.random())  #0.2746445568079129
print (random.uniform( 1 10 ))  #9.887001463194844
 
#随机字符:
print (random.choice( 'abcdefg&#%^*f' )) #f
 
#多个字符中选取特定数量的字符:
print (random.sample( 'abcdefghij' , 3 ))  #['f', 'h', 'd']
 
#随机选取字符串:
print ( random.choice ( [ 'apple' 'pear' 'peach' 'orange' 'lemon' ] ))  #apple
#洗牌#
items  =  [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ]
print (items)  #[1, 2, 3, 4, 5, 6, 7]
random.shuffle(items)
print (items)  #[1, 4, 7, 2, 5, 3, 6]

生成随机验证码:

1
2
3
4
5
6
7
8
9
10
import  random
checkcode  =  ''
for  in  range ( 4 ):
     current  =  random.randrange( 0 , 4 )
     if  current ! =  i:
         temp  =  chr (random.randint( 65 , 90 ))
     else :
         temp  =  random.randint( 0 , 9 )
     checkcode  + =  str (temp)
print  (checkcode)


3.os模块

提供对操作系统进行调用的接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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    输出用于分割文件路径的字符串
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所指向的文件或者目录的最后修改时间

更多点击这里


4.sys模块

1
2
3
4
5
6
7
8
sys.argv           命令行参数 List ,第一个元素是程序本身路径
sys.exit(n)        退出程序,正常退出时exit( 0 )
sys.version        获取Python解释程序的版本信息
sys.maxint         最大的 Int
sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform       返回操作系统平台名称
sys.stdout.write( 'please:' )
val  =  sys.stdin.readline()[: - 1 ]


5.shutil模块

参考http://www.cnblogs.com/wupeiqi/articles/4963027.html 


6.json和pickle模块


用于序列化的两个模块

  • json,用于字符串 和 python数据类型间进行转换

  • pickle,用于python特有的类型 和 python的数据类型间进行转换

Json模块提供了四个功能:dumps、dump、loads、load

pickle模块提供了四个功能:dumps、dump、loads、load

wKioL1e29DbjpR--AABUpCNKHV0613.png-wh_50


7. shelve模块

shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import  shelve
  
=  shelve. open ( 'shelve_test' #打开一个文件 
  
class  Test( object ):
     def  __init__( self ,n):
         self .n  =  n
  
  
=  Test( 123 )  
t2  =  Test( 123334 )
  
name  =  [ "alex" , "rain" , "test"
d[ "test" =  name  #持久化列表
d[ "t1" =  t       #持久化类
d[ "t2" =  t2
  
d.close()




  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值