# 内置模块
[TOC]
---
## datetime
```python
# 导入datetime模块的datetime类
from datetime import datetime
now = datetime.now()
now # datetime.datetime(2018, 3, 30, 21, 2, 20, 167446)
print(now) # 2018-03-30 21:02:20.167446
print(type(now)) # <class 'datetime.datetime'>
# 用指定日期时间创建datetime
dt = datetime(2015, 4, 19, 12, 20)
print(dt) # 2015-04-19 12:20:00
# 转换时间戳
dt = datetime(2018, 4, 19, 12, 20)
dt.timestamp() # 1524111600.0
# timestamp转换为datetime
t=1524111600
print(datetime.fromtimestamp(t)) # 2018-04-19 12:20:00
# str转换为datetime
cday = datetime.strptime('2018-3-30 21:36:50', '%Y-%m-%d %H:%M:%S')
print(cday) # 2018-03-30 21:36:50
# datetime转换为str
now = datetime.now()
print(now.strftime('%Y-%m-%d %H:%M:%S')) # 2018-03-30 21:42:24
# 10小时后
from datetime import timedelta
now = datetime.now()
now + timedelta(hours=10) # datetime.datetime(2018, 3, 31, 7, 44, 11, 686375)
# 1天前
now - timedelta(days=1)
# 2天12小时以后
now + timedelta(days=2, hours=12)
```
## collections
collections内置了很多有用的集合类
### namedtuple
语义化元祖(为tuple取名): namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。
```python
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
Point # <class '__main__.Point'>
p = Point(1,2)
p.x # 1
p.y # 2
isinstance(p,Point) # True
isinstance(p,tuple) # True
```
### deque
使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。
deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈:
```python
from collections import deque
q = deque(['a', 'b', 'c'])
q.append('x') # pop()
q.appendleft('y') #popleft()
q # deque(['y', 'a', 'b', 'c', 'x'])
```
### defaultdict
dict的key不存在时提供默认值
```python
from collections import defaultdict
dd = defaultdict(lambda: 'N/A') # 注意: 默认值是调用函数返回的
dd['key1'] = 'abc'
dd['key1'] # key1存在 'abc'
dd['key2'] # key2不存在,返回默认值 'N/A'
# 但如果默认值是不需要函数处理之后的结果值,建议用dict
```
### OrderedDict
使用dict时,Key是无序的。如果要保持Key的顺序,可以用OrderedDict
**注意:这里的顺序是指插入的顺序,而不是keys或value的大小顺序**
```python
od = OrderedDict([('b', 2), ('c', 3),('a', 1)])
od # OrderedDict([('b', 2), ('c', 3), ('a', 1)])
list(od.keys()) # ['b', 'c', 'a']
```
> 实现一个FIFO(先进先出)的dict类,当容量超出限制时,先删除最早添加的Key:
```python
class LastUpdatedOrderedDict(OrderedDict):
def __init__(self, capacity):
super().__init__()
self._capacity = capacity
def __setitem__(self, key, value):
containsKey = 1 if key in self else 0
if len(self) - containsKey >= self._capacity:
last = self.popitem(last=False)
print('remove:', last)
if containsKey:
del self[key]
print('set:', (key, value))
else:
print('add:', (key, value))
OrderedDict.__setitem__(self, key, value)
d = LastUpdatedOrderedDict(2);
d[0]=1 # add: (0, 1)
d[0]=0 # set: (0, 0)
d[1]=0 # add: (1, 0)
d[2]=0 # remove: (0, 0) add: (2, 0)
```
### counter
计数器
```python
from collections import Counter
c = Counter()
for ch in 'programming':
c[ch] = c[ch] + 1
c # Counter({'r': 2, 'g': 2, 'm': 2, 'p': 1, 'o': 1, 'a': 1, 'i': 1, 'n': 1})
```
## base64
```python
import base64
base64.b64encode(b'binary\x00string') # b'YmluYXJ5AHN0cmluZw=='
base64.b64decode(b'YmluYXJ5AHN0cmluZw==') # b'binary\x00string'
```
## hashlib
提供常见的摘要算法
```python
import hashlib
md5 = hashlib.md5()
md5.update('how to use md5 in python hashlib?'.encode('utf-8'))
print(md5.hexdigest()) # d26a53750bc40b38b65a520292f69306
# 可以分块多次调用update()
md5.update('how to use md5 in '.encode('utf-8'))
md5.update('python hashlib?'.encode('utf-8'))
# 加盐算法
import hmac
message = b'Hello, world!'
key = b'secret'
h = hmac.new(key, message, digestmod='MD5')
h.hexdigest() # fa4ee7d173f2d97ee79022d1a7355bcf
```
## itertools
```python
import itertools
# 生成一个无限迭代器,从1开始
natuals = itertools.count(1)
# 无限循环ABC
cs = itertools.cycle('ABC')
# 无限循环元素A,第二参数可限制次数
ns = itertools.repeat('A', 3)
```
### takewhile
通过takewhile()等函数根据条件判断来截取出一个有限的序列
```python
natuals = itertools.count(1)
ns = itertools.takewhile(lambda x: x <= 10, natuals)
list(ns) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
### chain
串联迭代对象
```python
for n in itertools.chain('xyz','abc'):
print(n)
# x y z a b c
```
### groupby
```python
# lamba: 上个返回的值和这个返回的值相等,就是相同分组的
for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
print(key, list(group))
```
## sys
## contextlib
处理上下文关系
## urllib
urllib提供了一系列用于操作URL的功能,但我们一般不用