datetime
获取当前日期和时间:
from datetime import datetime
now = datetime.now()
print(now)
# 2019-07-31 19:21:04.014963
获取指定日期和时间:
from datetime import datetime
dt = datetime(2015, 4, 19, 12, 20) # 用指定日期时间创建datetime
print(dt)
# 2015-04-19 12:20:00
datetime转换为timestamp:
timestamp = 0 = 1970-1-1 00:00:00 UTC+0:00
对应的北京时间是:
timestamp = 0 = 1970-1-1 08:00:00 UTC+8:00
from datetime import datetime
dt = datetime(2015, 4, 19, 12, 20) # 用指定日期时间创建datetime
dt.timestamp() # 把datetime转换为timestamp
print(dt)
# 1429417200.0
timestamp转换为datetime:
from datetime import datetime
t = 1429417200.0
dt = datetime.fromtimestamp(t)
print(dt)
# 2015-04-19 12:20:00
str转换为datetime:
from datetime import datetime
cday = datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S')
print(cday)
# 2015-06-01 18:19:59
print(type(cday))
#
datetime转换为str:
from datetime import datetime
now = datetime.now()
print(now.strftime('%a, %b %d %H:%M'))
# Wed, Jul 31 19:34
datetime加减:
from datetime import datetime, timedelta
now = datetime.now()
print(now) # 2019-07-31 19:36:45.824603
now = now + timedelta(hours=10)
print(now) # 2019-08-01 05:36:45.824603
now = now - timedelta(days=2, hours=12)
print(now) # 2019-07-29 17:36:45.824603
collections
- namedtuple
namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。
from collections import namedtuple
# Point = namedtuple(typename='Point', field_names=['x', 'y'])
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x) # 1
print(p.y) # 2
- deque
deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈:
from collections import deque
q = deque(['a', 'b', 'c'])
q.append('x')
q.appendleft('y')
print(q) # deque(['y', 'a', 'b', 'c', 'x'])
print(type(q)) #
- defaultdict
使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict:
from collections import defaultdict
dd = defaultdict(lambda: 'N/A')
dd['key1'] = 'abc'
print(dd['key1']) # abc
print(dd['key2']) # N/A
注意默认值是调用函数返回的,而函数在创建defaultdict对象时传入。除了在Key不存在时返回默认值,defaultdict的其他行为跟dict是完全一样的。
- OrderedDict
使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。如果要保持Key的顺序,可以用OrderedDict:
from collections import OrderedDict
d = dict([('a', 1), ('b', 2), ('c', 3)]) # dict的 Key是无序的
print(d) # {'a': 1, 'b': 2, 'c': 3}
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) # OrderedDict的 Key是有序的
print(od) # OrderedDict([('a', 1), ('b', 2), ('c', 3)])
print(od['a']) # 1
- Counter
Counter是一个简单的计数器,例如,统计字符出现的个数:
from collections import Counter
c = Counter()
for ch in 'programming':
c[ch] = c[ch] + 1
print(c) # Counter({'r': 2, 'g': 2, 'm': 2, 'p': 1, 'o': 1, 'a': 1, 'i': 1, 'n': 1})
- ChainMap
ChainMap可以把一组dict串起来并组成一个逻辑上的dict。ChainMap本身也是一个dict,但是查找的时候,会按照顺序在内部的dict依次查找。
from collections import ChainMap
a = {"x": 1, "z": 3}
b = {"y": 2, "z": 4}
c = ChainMap(a, b)
print(c) # ChainMap({'x': 1, 'z': 3}, {'y': 2, 'z': 4})
print("x: {}, y: {}, z: {}".format(c["x"], c["y"], c["z"])) # x: 1, y: 2, z: 3