day17

time模块

时间戳

时间戳(timestamp):时间戳表示的是从1970年1月1日00:00:00开始按秒计算 到现在的时间

import time

time_stamp = time.time()
print(time_stamp, type(time_stamp))

# 1569638627.6091728 <class 'float'>

格式化时间

格式化的时间字符串(format string):格式化时间表示的是普通的字符串格式的时间。

# 格式的-是拼接符号
format_time = time.strftime("%Y-%m-%d %X")
print(format_time, type(format_time))

# 2019-09-28 11:21:17 <class 'str'>

结构化时间

结构化的时间(struct time):struct_time元组共有9个元素共九个元素,分别为(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时)

print('本地时区的struct_time:
{}'.format(time.localtime()))
print('UTC时区的struct_time:
{}'.format(time.gmtime()))


'''
本地时区的struct_time:
time.struct_time(tm_year=2019, tm_mon=9, tm_mday=28, tm_hour=11, tm_min=22, tm_sec=2, tm_wday=5, tm_yday=271, tm_isdst=0)

UTC时区的struct_time:
time.struct_time(tm_year=2019, tm_mon=9, tm_mday=28, tm_hour=3, tm_min=22, tm_sec=2, tm_wday=5, tm_yday=271, tm_isdst=0)'''
# 结构化时间的基准时间
print(time.localtime(0))
# 结构化时间的基准时间上增加一年时间
print(time.localtime(3600*24*365))

三种格式时间的转换

结构化时间 , 定义 now_time

now_time = time.localtime()
print(now_time)

时间格式之间的转换

# 把结构化时间转换为时间戳格式
print(time.mktime(now_time))   


# 1569641093.0
# 把结构化时间转换为格式化时间
# %Y年-%m月-%d天 %X时分秒=%H时:%M分:%S秒
print(time.strftime("%Y-%m-%d %X", now_time))


# 2019-09-28 11:26:18
# 把格式化时间化为结构化时间,它和strftime()是逆操作
print(time.strptime('2013-05-20 13:14:52', '%Y-%m-%d %X'))


# time.struct_time(tm_year=2013, tm_mon=5, tm_mday=20, tm_hour=13, tm_min=14, tm_sec=52, tm_wday=0, tm_yday=140, tm_isdst=-1)
# 把结构化时间表示为这种形式:'Sun Jun 20 23:21:05 1993'。
print(time.asctime())


# Sat Sep 28 11:26:47 2019

其他了解用法

# 推迟指定的时间运行,单位为秒
start = time.time()
time.sleep(3)
end = time.time()

print(end-start)

datetime模块

用于时间的加减

import datetime

# 返回当前时间
print(datetime.datetime.now())

# 当前时间+3天
print(datetime.datetime.now() + datetime.timedelta(3))

# 当前时间-3天
print(datetime.datetime.now() + datetime.timedelta(-3))

# 当前时间-3小时
print(datetime.datetime.now() + datetime.timedelta(hours=3))

# 当前时间+30分钟
print(datetime.datetime.now() + datetime.timedelta(minutes=30))

# 时间替换
c_time = datetime.datetime.now()
print(c_time.replace(minute=20, hour=5, second=13))

hashlib模块

hashlib用于加密

hashlib模块特点:

  1. 只要使用的hash算法不变,无论校验的内容有多大 , 结果永远都是相同长度的字符串
  2. 叠加性

hashlib基本用法

import hashlib

m = hashlib.md5()
m.update('hello'.encode('utf8'))
print(m.hexdigest())

# 5d41402abc4b2a76b9719d911017c592



m2 = hashlib.md5()
m2.update('hellohash'.encode('utf8'))
print(m2.hexdigest())

# 97fa850988687b8ceb12d773347f7712

hashlib撞库破解

import hashlib

# 假定我们知道hash的微信会设置如下几个密码
pwd_list = [
    'hash3714',
    'hash1313',
    'hash94139413',
    'hash123456',
    '123456hash',
    'h123ash',
]


def make_pwd_dic(pwd_list):
    dic = {}
    for pwd in pwd_list:
        m = hashlib.md5()
        m.update(pwd.encode('utf-8'))
        dic[pwd] = m.hexdigest()
    return dic


def break_code(hash_pwd, pwd_dic):
    for k, v in pwd_dic.items():
        if v == hash_pwd:
            print('hash的微信的密码是===>%s' % k)


hash_pwd = '0562b36c3c5a3925dbe3c4d32a4f2ba2'
break_code(hash_pwd, make_pwd_dic(pwd_list))

hash的微信的密码是===>hash123456

hmac模块

hmac和hashlib相似,但是会有一个加盐(秘钥) , 特点与hashlib相同

import hmac

# 注意hmac模块只接受二进制数据的加密
h1 = hmac.new(b'hash')
h1.update(b'hello')
h1.update(b'world')
print(h1.hexdigest())

# 905f549c5722b5850d602862c34a763e

h2 = hmac.new(b'hash')
h2.update(b'helloworld')
print(h2.hexdigest())

# 905f549c5722b5850d602862c34a763e

typing模块

typing模块的作用:

  1. 类型检查,防止运行时出现参数和返回值类型不符合。
  2. 作为开发文档附加说明,方便使用者调用时传入和返回参数类型。
  3. 该模块加入后并不会影响程序的运行,不会报正式的错误,只有提醒。
  • 注意:typing模块只有在python3.5以上的版本中才可以使用,pycharm目前支持typing检查

typing模块的使用

from typing import List, Tuple, Dict

# 指定函数参数的数据类型
def add(a: int, string: str, f: float,
        b: bool) -> Tuple[List, Tuple, Dict, bool]:
    list1 = list(range(a))
    tup = (string, string, string)
    d = {"a": f}
    bl = b
    return list1, tup, d, bl


print(add(5, "hhhh", 2.3, False))

# ([0, 1, 2, 3, 4], ('hhhh', 'hhhh', 'hhhh'), {'a': 2.3}, False)
  • 在传入参数时通过"参数名:类型"的形式声明参数的类型;
  • 返回结果通过"-> 结果类型"的形式声明结果的类型。
  • 在调用的时候如果参数的类型不正确pycharm会有提醒,但不会影响程序的运行。
  • 对于如list列表等,还可以规定得更加具体一些,如:"-> List[str]”,规定返回的是列表,并且元素是字符串。

typing模块常用类型

  • int、long、float: 整型、长整形、浮点型
  • bool、str: 布尔型、字符串类型
  • List、 Tuple、 Dict、 Set:列表、元组、字典、集合
  • Iterable、Iterator:可迭代类型、迭代器类型
  • Generator:生成器类型

request模块

request模块 常用于爬虫 , 作用是模拟浏览器对url发送请求,拿到数据

import requests

response = requests.get('https://ishuo.cn')
data = response.text
print(data)

# 常与re模块连用

re模块

re模块 , 即正则表达式 , 本身是一种小型的、高度专业化的编程语言,它并不是Python的一部分

re模块的作用就是: 从大的字符串中挑选出 具有某种形状特点的字符串

常用元字符

^ : 以..开头

s = 'abcdabc' 
res = re.findall('^ab', s)
print(res)  

# ['ab']

$ : 以..结尾

s = 'abcdabc'
res = re.findall('bc$', s)
print(res)  

# ['bc']

. : 任意字符

s = 'abc红abc'
res = re.findall('abc.', s)
print(res)  

# ['abc红']

d : 数字

s = 'skld2342ljk'
res = re.findall('d', s)
print(res)  

# ['2', '3', '4', '2']

D : 非数字

s = 'skld2342ljk'
res = re.findall('D', s)
print(res)

# ['s', 'k', 'l', 'd', 'l', 'j', 'k']

w : 非空字符,即数字字母下划线

s = 'skld_2你3 42ljk'
res = re.findall('w', s)
print(res)

# ['s', 'k', 'l', 'd', '_', '2', '你', '3', '4', '2', 'l', 'j', 'k']

W : 空字符,包括空格 换行

s = 'skld_23 42ljk'
res = re.findall('W', s)
print(res)

# [' ']

s : 空字符,包括空格 换行

s = 'skld_23 42ljk'
res = re.findall('s', s)
print(res)

# [' ']

S : 非空字符,即数字字母下划线

s = 'skld_23 42ljk'
res = re.findall('S', s)
print(res)

# ['s', 'k', 'l', 'd', '_', '2', '3', '4', '2', 'l', 'j', 'k']

+ : 前面的一个字符至少1个 [1,正无穷)

s = 'abcddabdabcdd abcd abc'
print(re.findall('abcd+', s))

# ['abcdd', 'abcdd', 'abcd']

?:前面的一个字符0-1个 前一个字符[0,1] 最大只有一个

s = 'abcddddd abcd abc ab'
print(re.findall('abcd?', s))

# ['abcd', 'abcd', 'abc']

*** :前面的一个字符至少0个 前一个字符[0,正无穷)**

s = 'abcddddd abcd abc ab'
print(re.findall('abcd*', s))

# ['abcddddd', 'abcd', 'abc']

[] : 中括号内的都可以 , 但是只占一个位置

s = 'abc bbc cbc dbc abcd '
print(re.findall('[abc]bc', s))

# ['abc', 'bbc', 'cbc', 'abc']

[^] : 中括号的都不可以

s = 'abc bbc cbc dbc'
print(re.findall('[^abc]bc', s))

# ['dbc']

|:或 满足就打印 , 一个或者两个三个

s = 'abc bbd dbc'
print(re.findall('abc|bbc', s))

# ['abc']

{2}:前面的字符重复2个

s = 'abccabc abccc'
print(re.findall('abc{2}', s))

# ['abcc', 'abcc']

{1,2}:前面的字符重复1-2个 区间是[1,2]

s = 'abccabc abccc'
print(re.findall('abc{1,2}', s))

# ['abcc', 'abc', 'abcc']

特殊构造

a(?=d) :a后面是数字,但是不要数字,不消耗字符串内容

s = 'a123 aaaa a234 abc'
#    a1   aa
#          aa
#           aa 
#               a2  ab

print(re.findall('a(?=d)', s))
# ['a', 'a']

print(re.findall('a(?=w)', s))
# ['a', 'a', 'a', 'a', 'a', 'a']

贪婪模式

Python里数量词默认是贪婪的,总是尝试匹配尽可能多的字符 , 一定要找到最后 才停止

.(任意字符)*(0-无穷个)

s = 'abcdefgbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbg'
print(re.findall('a.*g', s))

# ['abcdefgbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbg']

非贪婪模式

非贪婪的则相反,总是尝试匹配尽可能少的字符 , 找到一个就停止并返回

.(任意字符)*(0-无穷个)?(让他进入非贪婪模式)

s = 'abcdefgbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbg'
print(re.findall('a.*?g', s))

# ['abcdefg']

re的常用函数

findall:最常用 推荐使用 直接在函数内部书写匹配规则

import re
a = re.findall("匹配规则", "这个字符串是否有匹配规则的字符")
print(a)

compile:写一个特定的规则模板

# 定义邮箱、手机号匹配规则,直接调用
email_pattern = re.compile('w+@w+.com')
phone_patter = re.compile('d{13}')
print(re.findall(email_pattern, s))

match: 从字符串开头找一个,找得到就不找了 ;找不到报错

s = 'ab abcddd abc'
res = re.match('abcd*', s)
print(res.group())

search: 搜索,从整个内容中匹配,只找一个,找不到报错

s = 'ab abcddd abc'
res = re.search('abcd*', s)
print(res.group())

split 切割,相当于字符串的split

s = 'ab23423abcddd234234abcasdfjlasjdk234l23lk4j2kl34kl25k3j2kl3j5lkj'
print(re.split('d+', s))

# ['ab', 'abcddd', 'abcasdfjlasjdk', 'l', 'lk', 'j', 'kl', 'kl', 'k', 'j', 'kl', 'j', 'lkj']

sub 替换,相当于字符串的replace

s = 'ab23423abcddd234234abcasdfjlasjdk234l23lk4j2kl34kl25k3j2kl3j5lkj'
print(re.sub('d+', ' ', s))

# ab abcddd abcasdfjlasjdk l lk j kl kl k j kl j lkj

subn 替换,会返回替换的次数

s = 'ab23423abcddd234234abcasdfjlasjdk234l23lk4j2kl34kl25k3j2kl3j5lkj'
print(re.subn('d+', ' ', s))

# ('ab abcddd abcasdfjlasjdk l lk j kl kl k j kl j lkj', 12)

re模块补充

re.S 会让.匹配换行符

a = '''asdfhellopass:
    worldaf
    '''
b = re.findall('hello(.*?)world', a)
c = re.findall('hello(.*?)world', a, re.S)
print(b)
# []

print(c)
# ['pass:
    ']

. 不匹配换行

s = '''abc
abcabc*abc
'''
print(re.findall('abc.abc', s))  
# ['abc*abc']

print(re.findall('abc.abc', s, re.S))  
# ['abc
abc', 'abc*abc']

分组 --> 只要括号里的(...)

s = 'abc abcd abcdd'
print(re.findall('a(.)c(d)', s))

# [('b', 'd'), ('b', 'd')]

有名分组

s = 'abc abcd abcdd'
print(re.search('a(?P<name>.)c(?P<name2>d)', s).groupdict())

# {'name': 'b', 'name2': 'd'}

关于re模块必须知道的知识点

  1. .*? :

非贪婪匹配

  1. 贪婪和非贪婪:

    贪婪匹配:在满足匹配时,匹配尽可能长的字符串,默认情况下,采用贪婪匹配

    非贪婪匹配(?):在满足匹配时,找到一个就停止,返回结果

  2. findall:

    findall(pattern, string, flags=0) 浏览全部字符串,匹配所有合规则的字符串,匹配到的字符串放到一个列表中,未匹配成功返回空列表

  3. re.S:

    表示 “.” 的作用扩展到整个字符串,包括“ ”。看如下代码:

  4. match和sarch的区别:

    match()函数只在string的开始位置匹配,找不到就报错
    search()会扫描整个string查找匹配,会扫描整个字符串并返回第一个成功的匹配结果

  5. 分组:

    ()表示分组,可以与 | 合用,(ab|cd)表示匹配字符 ab 或 字符 cd

  6. 有名分组:

    ?P<name> # ?P<>定义组里匹配内容的key(键),<>里面写key名称,值就是匹配到的内容(只对正则函数返回对象时有用)

原文地址:https://www.cnblogs.com/TZ0503/p/11605117.html