time模块
在Python中,通常有这三种方式来表示时间:时间戳、元组(struct_time)、格式化的时间字符串:
(1)时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
(2)格式化的时间字符串(Format String): ‘1999-12-06’
python中时间日期格式化符号:
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身
(3)元组(struct_time) :struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天等
索引(Index) | 属性(Attribute) | 值(Values) |
---|---|---|
0 | tm_year(年) | 比如2011 |
1 | tm_mon(月) | 1 - 12 |
2 | tm_mday(日) | 1 - 31 |
3 | tm_hour(时) | 0 - 23 |
4 | tm_min(分) | 0 - 59 |
5 | tm_sec(秒) | 0 - 60 |
6 | tm_wday(weekday) | 0 - 6(0表示周一) |
7 | tm_yday(一年中的第几天) | 1 - 366 |
8 | tm_isdst(是否是夏令时) | 默认为0 |
1 import time 2 # print(time.time()) 3 # print(time.strftime("%Y-%m-%d %H:%M:%S")) 4 # print(time.strftime("%Y/%m/%d %H:%M:%S")) 5 # t1 = 1500000000 6 # t2 = 1600000000 7 # st1 = time.localtime(t1) 8 # st2 = time.localtime(t2) 9 # st3 = time.localtime(t2-t1) 10 # t4 = time.strftime(‘%Y-%m-%d %H:%M:%S‘,(st3[0]-1970,*st3[1:])) 11 # print(st3.tm_yday,st3.tm_hour,st3.tm_min,st3.tm_sec) 12 13 # def past_time(start_time = None): 14 # start_time = start_time if start_time else time.time() 15 # n = 0 16 # while n<100: 17 # time.sleep(0.5) 18 # end_time = time.time() 19 # st = time.gmtime(end_time-start_time) 20 # print(‘year:%s day:%s %s:%s:%s‘% (st.tm_year-1970,st.tm_yday-1,st.tm_hour,st.tm_min,st.tm_sec)) 21 # n += 1 22 # past_time() 23 24 # 时间戳和结构化时间 25 # t = time.time() 26 # print(t) 27 # print(time.localtime(t)) 28 # print(time.gmtime(t)) 29 # print(time.mktime(time.localtime(t))) 30 # print(time.mktime(time.gmtime(8*3600))) 31 32 # asctime([tuple]) -> string 33 # print(time.asctime()) 34 # Convert a time tuple to a string, e.g. ‘Sat Jun 06 16:26:11 1998‘. 35 # When the time tuple is not present, current time as returned by localtime() 36 # is used. 37 38 # strptime(string, format) -> struct_time 39 # Parse a string to a time tuple according to a format specification. 40 # print(time.strptime(‘2000-12.31‘,‘%Y-%m.%d‘)) 41 # # time.struct_time(tm_year=2000, tm_mon=12, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=366, tm_isdst=-1) 42 43 # print(time.strftime(‘%m/%d/%Y %H:%M:%S‘,time.localtime(3000000000))) # 01/24/2065 13:20:00
collections模块
在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter、deque、defaultdict、namedtuple和OrderedDict等。
1.namedtuple: 生成可以使用名字来访问元素内容的tuple
2.deque: 双端队列,可以快速的从另外一侧追加和推出对象
3.Counter: 计数器,主要用来计数
4.OrderedDict: 有序字典
5.defaultdict: 带有默认值的字典
1 # from collections import namedtuple 2 # Point = namedtuple(‘point‘,[‘x‘,‘y‘,‘z‘]) 3 # p1 = Point(1,2,3) 4 # print(p1) 5 # print(p1.x,p1.y,p1.z) 6 # p2 = Point(2,3,4) 7 # print(p2.x,p2.y,p2.z) 8 9 # Card = namedtuple(‘card‘,[‘suits‘,‘number‘]) 10 # print(Card.__doc__) 11 # c1 = Card(‘红桃‘,3) 12 # print(c1.suits,c1.number) 13 14 # >>> from collections import namedtuple 15 # >>> Point = namedtuple(‘Point‘,[‘x‘,‘y‘]) 16 # >>> Point.__doc__ 17 # ‘Point(x, y)‘ 18 # >>> p = Point(11,y=22) 19 # >>> p[0] + p[1] 20 # 33 21 # >>> p.x+p.y 22 # 33 23 # >>> a,b = p 24 # >>> a,b 25 # (11, 22) 26 # >>> a 27 # 11 28 # >>> b 29 # 22 30 # >>> d = p._asdict() 31 # >>> print(d) 32 # OrderedDict([(‘x‘, 11), (‘y‘, 22)]) 33 # >>> print(d[‘x‘]) 34 # 11 35 # >>> Point(**d) 36 # Point(x=11, y=22) 37 # >>> p._replace(x=100) 38 # Point(x=100, y=22) 39 40 # 队列 41 # import queue 42 # q = queue.Queue() 43 # # Create a queue object with a given maximum size. 44 # # If maxsize is <= 0, the queue size is infinite. 45 # q.put([1,2,3]) 46 # q.put(5) 47 # q.put(6) 48 # print(q) 49 # print(q.qsize()) 50 # print(q.get()) 51 # print(q.get()) 52 # print(q.get()) 53 # print(q.qsize()) 54 55 # from collections import deque 56 # dq = deque(‘adgas465a‘) 57 # print(dq) 58 # # print(dq.pop()) 59 # # print(dq.pop()) 60 # dq.append(‘a‘) 61 # dq.append(‘b‘) 62 # dq.appendleft(‘c‘) 63 # print(dq) 64 # print(dq.pop()) 65 # print(dq.popleft()) 66 67 # 有序字典 68 # from collections import OrderedDict 69 # od = OrderedDict([(‘a‘,1),(‘b‘,2),(‘c‘,3)]) 70 # print(od) 71 # print(od[‘a‘]) 72 # print(od[‘b‘]) 73 # for k in od: 74 # print(k,od[k]) 75 76 # ??????? 77 # from collections import defaultdict 78 # d = defaultdict(lambda : 5) 79 # print(d) 80 81 # from collections import Counter 82 # Counter(): Create a new, empty Counter object. And if given, count elements 83 # from an input iterable. Or, initialize the count from another mapping 84 # of elements to their counts. 85 # c = Counter(‘sdfjkasjdflajs‘) 86 # print(c) # Counter({‘s‘: 3, ‘j‘: 3, ‘a‘: 2, ‘d‘: 2, ‘f‘: 2, ‘k‘: 1, ‘l‘: 1}) 87 # c[‘d‘] -= 1 88 # print(c) # Counter({‘j‘: 3, ‘s‘: 3, ‘f‘: 2, ‘a‘: 2, ‘k‘: 1, ‘d‘: 1, ‘l‘: 1}) 89 90 # c = Counter() # a new, empty counter 91 # print(c) # Counter() 92 # c = Counter(‘gallahad‘) # a new counter from an iterable 93 # print(c) # Counter({‘a‘: 3, ‘l‘: 2, ‘d‘: 1, ‘g‘: 1, ‘h‘: 1}) 94 # c = Counter({‘a‘: 4, ‘b‘: 2}) # a new counter from a mapping 95 # print(c) # Counter({‘a‘: 4, ‘b‘: 2}) 96 # c = Counter(a=4, b=2) # a new counter from keyword args 97 # print(c) # Counter({‘a‘: 4, ‘b‘: 2})
defaultdict
1 from collections import defaultdict 2 3 values = [11, 22, 33,44,55,66,77,88,99,90] 4 5 my_dict = defaultdict(list) 6 7 for value in values: 8 if value>66: 9 my_dict[‘k1‘].append(value) 10 else: 11 my_dict[‘k2‘].append(value)
random模块
1 # import random 2 # random.random() # Get the next random number in the range [0.0, 1.0) 3 # print(random.random()) 4 5 # random.uniform(a,b) # Get a random number in the range [a, b) or [a, b] depending on rounding. 6 # a = random.uniform(1,3) 7 # print(a) 8 9 # print(random.randint(1,5)) # 大于等于1小于等于5之间的整数 10 11 # print(random.choice([1,‘23‘,[4,5]])) # 1或者23或者[4,5] 12 # print(random.choice(1)) # TypeError: object of type ‘int‘ has no len() 13 14 # print(random.sample([1,‘23‘,[4,5]],2)) # 随机返回[1,‘23‘,[4,5]]中的两个元素,返回的是一个列表 15 # 16 # print(random.sample(list({‘k1‘:‘v1‘,‘k2‘:‘v2‘}),2)) # [‘k1‘, ‘k2‘] 17 18 # 打乱列表顺序 19 # item = [1,3,5,7,9] 20 # random.shuffle(item) 21 # print(item) 22 23 # 生成验证码 24 # import random 25 # def v_code(n=5): 26 # code = ‘‘ 27 # for i in range(n): 28 # num = random.randint(0,9) 29 # alf = chr(random.randint(65,90)) 30 # add = random.choice([num,alf]) 31 # code += str(add) 32 # return code 33 # print(v_code()) 34 35 # import random 36 # def v_code(n=5): 37 # code = ‘‘ 38 # for i in range(n): 39 # num = random.randint(0,9) 40 # alf = chr(random.randint(65,90)) 41 # add = random.choice([num,alf]) 42 # code = ‘‘.join([code,str(add)]) 43 # return code 44 # print(v_code())
os模块
1 import os 2 # print(os.getcwd()) # Return a unicode string representing the current working directory 3 4 # os.chdir(r‘E:\\Python_Fullstack_S9‘) # Change the current working directory to the specified path. 5 # print(os.getcwd()) 6 7 # os.makedirs(‘dirname1/dirname2/dirname3‘) 8 # os.removedirs(‘dirname1/dirname2/dirname3‘) 9 # os.mkdir(‘dirname1/dirname2/dirname3‘) 10 11 # print(os.listdir(r‘E:\\Python_Fullstack_S9‘)) 12 13 # stat 系统调用时用来返回相关文件的系统状态信息的 14 # sta=os.stat(‘collections_module.py‘) 15 # print(sta) 16 # os.stat_result(st_mode=33206, # 权限模式 17 # st_ino=5910974510945247, # inode number 18 # st_dev=284297630, # device 19 # st_nlink=1, # number of hard links 20 # st_uid=0, # 所有用户的user id 21 # st_gid=0, # 所有用户的group id 22 # st_size=1641, # 文件的大小,以位为单位 23 # st_atime=1515569689, # 文件最后访问时间 24 # st_mtime=1515569689, # 文件最后修改时间 25 # st_ctime=1515566554) # 文件创建时间 26 27 # python os.stat() 和 stat模块详解: http://www.cnblogs.com/maseng/p/3386140.html 28 29 # print(os.sep) # \\ 30 31 # os.system(‘dir‘) 32 # ret = os.popen(‘dir‘).read() 33 # print(ret) 34 # print(os.environ) 35 36 # print(os.getcwd()) # E:\\Python_Fullstack_S9\\Python_Fulldeck_S9_20171214\\day19 37 # print(os.path.split(os.getcwd())) # (‘E:\\\\Python_Fullstack_S9\\\\Python_Fulldeck_S9_20171214‘, ‘day19‘) 38 39 # print(os.path.join(r‘C:\\Users\\Administrator‘,‘user‘,‘local‘)) 40 # print(os.getcwd()) 41 # print(os.path.getsize(os.path.join(os.getcwd(),‘time_module.py‘)))
sys模块
sys模块是与python解释器交互的一个接口
sys.argv 命令行参数List,第一个元素是程序本身路径 sys.exit(n) 退出程序,正常退出时exit(0),错误退出sys.exit(1) sys.version 获取Python解释程序的版本信息 sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 sys.platform 返回操作系统平台名称
1 import sys 2 # print(sys.platform) 3 # print(sys.version) 4 5 # print(sys.path.clear()) 6 7 # ret = sys.argv 8 # name = ret[1] 9 # pwd = ret[2] 10 # if name == ‘alex‘ and pwd == ‘alex3714‘: 11 # print(‘success‘) 12 # else: 13 # print(‘error‘) 14 # sys.exit() 15 # print(‘go on ....‘)