python常用模块
一、time
时间相关的操作,时间有三种表示方式:
- 时间戳 1970年1月1日之后的秒,即:time.time()
- 格式化的字符串 2014-11-11 11:11, 即:time.strftime('%Y-%m-%d')
- 结构化时间 元组包含了:年、日、星期等... time.struct_time 即:time.localtime()
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) time.struct_time(tm_year=2016, tm_mon=5, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=143, tm_isdst=-1) struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳 print(struct_2_stamp) 1463846400.0 #将时间戳转为字符串格式 print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式 time.struct_time(tm_year=2016, tm_mon=11, tm_mday=13, tm_hour=8, tm_min=48, tm_sec=46, tm_wday=6, tm_yday=318, tm_isdst=0) print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式 2016-11-14 08:52:46 #时间加减 import datetime print(datetime.datetime.now()) #返回2016-11-14 17:03:28.373055 print(datetime.date.fromtimestamp(time.time()) ) # 时间戳直接转成日期格式 2016-11-14 print(datetime.datetime.now() ) #返回2016-11-14 17:05:35.290132 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)) # 时间替换
Directive
Directive | Meaning | Notes |
---|---|---|
%a |
Locale’s abbreviated weekday name. | |
%A |
Locale’s full weekday name. | |
%b |
Locale’s abbreviated month name. | |
%B |
Locale’s full month name. | |
%c |
Locale’s appropriate date and time representation. | |
%d |
Day of the month as a decimal number [01,31]. | |
%H |
Hour (24-hour clock) as a decimal number [00,23]. | |
%I |
Hour (12-hour clock) as a decimal number [01,12]. | |
%j |
Day of the year as a decimal number [001,366]. | |
%m |
Month as a decimal number [01,12]. | |
%M |
Minute as a decimal number [00,59]. | |
%p |
Locale’s equivalent of either AM or PM. | (1) |
%S |
Second as a decimal number [00,61]. | (2) |
%U |
Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. | (3) |
%w |
Weekday as a decimal number [0(Sunday),6]. | |
%W |
Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. | (3) |
%x |
Locale’s appropriate date representation. | |
%X |
Locale’s appropriate time representation. | |
%y |
Year without century as a decimal number [00,99]. | |
%Y |
Year with century as a decimal number. | |
%z |
Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59]. | |
%Z |
Time zone name (no characters if no time zone exists). | |
%% |
A literal '%' character. |
二、random
#随机数 import random print(random.random()) print(random.randint(1,3)) #随机打印1到3的数字,3会显示 print(random.randrange(1,5)) #随机打印1到5之间的数字5不会显示
import string str_source = string.ascii_letters + string.digits print("".join(random.sample(str_source,7))) #打印随机数包括大小写数字
#生成随机验证码
import random
checkcode = "" for i in range(8): current = random.randrange(0,8) if current !=i: temp = chr(random.randint(65,90)) else: temp = random.randint(0,9) checkcode +=str(temp) print(checkcode)
三、re
re模块用于python的正则表达式的操作
'.' 默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行 '^' 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE) '$' 匹配字符结尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以 '*' 匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac") 结果为['abb', 'ab', 'a'] '+' 匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab', 'abb'] '?' 匹配前一个字符1次或0次 '{m}' 匹配前一个字符m次 '{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb', 'ab', 'abb'] '|' 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC' '(...)' 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abcabca456c
'\A' 只从字符开头匹配,re.search("\Aabc","alexabc") 是匹配不到的 '\Z' 匹配字符结尾,同$ '\d' 匹配数字0-9 '\D' 匹配非数字 '\w' 匹配[A-Za-z0-9] '\W' 匹配非[A-Za-z0-9] 's' 匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 结果 '\t' '(?P<name>...)' 分组匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 结果{'province': '3714', 'city': '81', 'birthday': '1993'}
最常用的匹配语法
re.match 从头开始匹配
re.search 匹配包含
re.findall 把所有匹配到的字符放到以列表中的元素返回
re.splitall 以匹配到的字符当作列表分隔符
re.sub 匹配字符并替换
import re #1、#group和groups a = "123abc456" print(re.search("([0-9]*)([a-z]*)([0-9]*)", a).group()) #打印整行 123abc456 print(re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(0)) #打印整行 123abc456 print(re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(1)) #打印123 print(re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(2)) #打印abc print(re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(3)) #打印456 print(re.search("([0-9]*)([a-z]*)([0-9]*)", a).groups()) #以元组的形式打印 ('123', 'abc', '456') #2、sub(pattern, repl, string, count=0, flags=0) 用于替换匹配的字符串 content = "123abc456" new_content = re.sub('\d+', 'hello', content) print(new_content) #替换,将所有数字替换成hello helloabchello ## 相比于str.replace功能更加强大 #3、findall(pattern, string, flags=0) #上述两中方式均用于匹配单值,即:只能匹配字符串中的一个,如果想要匹配到字符串中所有符合条件的元素,则需要使用 findall。 obj = re.findall("\d","abc123def456lmn") print(obj) #结果以列表的形式显示 ['1', '2', '3', '4', '5', '6'] #4、split((pattern, string, maxsplit=0, flags=0)) #根据指定匹配进行分组 content = "1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )" new_content = re.split("\*",content) print(new_content) #以*为分隔符进行分割 ["'1 - 2 ", ' ((60-30+1', '(9-2', '5/3+7/3', '99/4', '2998+10', '568/14))-(-4', '3)/(16-3', "2) )'"] new_content2 = re.split("[\+\-\*\/]+",content) print(new_content2) #["'1 ", ' 2 ', ' ((60', '30', '1', '(9', '2', '5', '3', '7', '3', '99', '4', '2998', '10', '568', '14))', '(', '4', '3)', '(16', '3', "2) )'"] inpp = '1-2*((60-30 +(-40-5)*(9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2))' inpp = re.sub("\s","",inpp) #print(inpp) new_content3 = re.split("\(([+\-\*\/]?\d+[\+\-\*\/]?\d+)",inpp,1) print(new_content3) #['1-2*(', '60-30', '+(-40-5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'] #5、search(pattern, string, flags=0) #根据模型去字符串匹配指定内容,匹配单个 obj = re.search("\d","ab123def2323adef") if obj: print(obj.group()) #结果显示 1 #6、match(pattern, string, flags=0) #从起始位置开始根据模型去字符串匹配指定内容,匹配单个 a = re.match("\d+","ab123def2323adef") if obj: print(obj.group()) #结果显示 1