Python_day9:常用内建模块

 

Python

PHP

常用内建模块

 

 

datetime

处理时间和日期

 

获取当前时间和日期

from datetime import datetime
now = datetime.now()
  print(now)

 

获取指定日期的时间

dt = datetime(1992,4,12,12,12,12)
  print(dt)

 

将datetime转换成时间戳

dt2tm = datetime.now().timestamp()
  print(dt2tm)

 

将timestamp转换成datetime

tm2dt= datetime.fromtimestamp(dt2tm)
  print(tm2dt)

 

字符串转换成datetime

cday = datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S')
  print(cday)

 

datetime转换成str

print(now.strftime('%a, %b %d %H:%M'))

 

datetime增减运算

now= datetime.now()
res = now+ timedelta(hours=10)
  print(res)

 

tt = '2015-1-21 9:01:30'
  s2d = datetime.strptime(tt, '%Y-%m-%d %H:%M:%S')
  d2t = s2d.timestamp()
  print(d2t)

 

 

 

time()

date()

 

Python

PHP

collections

一些常用类的集合

 

namedtuple

from collections import namedtuple
Point = namedtuple('Point',['x','y'])
res = Point(1,2)
  print(res.x)

用函数定义的形式形成一个自定义的tuple对象

 

deque

from collections import deque
q = deque(['a','b','c'])
q.append('d')
q.appendleft('0')
q.pop()
  print(q)

高效的可操作list

 

defaultdict

from collections import defaultdict
dd = defaultdict(lambda :'N/A')
dd['key1']='abc'
  print(dd['key1'])
  print(dd['key2'])

一个找不到键值对返回默认值的dict

 

OrderedDict

from collections import OrderedDict
d = dict([('a', 1), ('b', 2), ('c', 3)])
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
od[3] = 1
  print(d)
  print(od)

形成一个有序存在的dict

 

counter

from collections import Counter
c = Counter()
  for ch in 'programming':
    c[ch] = c[ch]+1
  print(c)

一个dict形式的计数器

 

 

Python

PHP

base64

import base64
res = base64.b64encode(b'binary\x00string')
res = base64.b64decode(res)
  print(res)
res = base64.urlsafe_b64encode(b'i\xb7\x1d\xfb\xef\xff')
res = base64.urlsafe_b64decode(res)
  print(res)

 

Base64适用于小段内容的编码,比如数字证书签名、Cookie的内容等

 

struct

import struct
res = struct.pack('>I', 10240099)
  print(res)
  
res = struct.unpack('>IH', b'\xf0\xf0\xf0\xf0\x80\x80')
  print(res)

structpack函数把任意数据类型变成bytes

 

hashlib

md532位):

import hashlib
md5 = hashlib.md5()
md5.update('how to use md5 in python hashlib?'.encode('utf-8'))
  print(md5.hexdigest())

sha140位)(与md5相似):

import hashlib
  sha1 = hashlib.sha1()
  sha1.update('how to use md5 in python hashlib?'.encode('utf-8'))
  print(sha1.hexdigest())

 

任意长度的数据转换为一个长度固定的数据串,通常用16进制的字符串表示

 

用户密码加盐后再加密

 

hmac

import hmac
message = b'Hello, world!'
  key = b'secret'
  h = hmac.new(key,message,digestmod='MD5')
print(h.hexdigest())

通过一个标准算法,在计算哈希的过程中,把key混入计算过程中

 

 

Python

PHP

itertools

count():无限计数

import itertools
natuals = itertools.count(1)
  for n in natuals:
    print(n)

cycle():无限循环

import itertools
natuals = itertools.cycle('ABC')
  for n in natuals:
    print(n)

repeat():无限重复/指定重复

import itertools
ns = itertools.repeat('A', 3)
  for n in ns:
    print(n)

 

 

takewhile()

import itertools
natuals = itertools.count(1)
ns = itertools.takewhile(lambda x: x <= 10, natuals)
  print(list(ns))

迭代结束条件

 

chain()

import itertools
  for c in itertools.chain('ABC', 'XYZ'):
    print(c)

连接

 

groupby()

import itertools
  for key, group in itertools.groupby('AaABBBCCAaA',lambda c: c.upper()):
    print(key, list(group))

相邻重复元素分组,lambda为可选参数

 

 

Python

PHP

contextlib

with open('/path/to/file', 'r') as f:

    f.read()

 

urllib

from urllib import request

with request.urlopen('https://api.douban.com/v2/book/2129650') as f:
   
data = f.read()
   
print('Status:',f.status,f.reason)
   
for k,v in f.getheaders():
       
print('%s:%s' % (k,v) )
   
print('Data:',data.decode('utf-8'))

get请求一个网页链接

 

 

from urllib import request
req
= request.Request('http://www.douban.com/')
req.add_header(
'User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
with request.urlopen(req) as f:
   
data = f.read()
   
print('Status:',f.status,f.reason)
   
for k,v in f.getheaders():
       
print('%s:%s' % (k,v) )
   
print('Data:',data.decode('utf-8'))

get模拟手机版浏览器,需要使用Request对象添加头部

 

 

post以及 proxy_handler…

 

XML解析

 

 

HTMLParser

 

 

猜你喜欢

转载自blog.csdn.net/zhq_zvik/article/details/80938244
今日推荐