1-datetime
#1-获取当前日期和时间 from datetime import datetime now = datetime.now() #当前时间 print(now) #2015-05-18 16:28:07.198690 #2-获取指定日期的时间 dt = datetime(2015,4,19,12,20) print(dt) #2015-04-19 12:20:00 #3-datetime转换为timestamp dt = datetime(2015,4,19,12,20) print(dt.timestamp()) #1429417200.0 把datetime转换为timestamp #某些编程语言(如Java和JavaScript)的timestamp使用整数表示毫秒数, #这种情况下只需要把timestamp除以1000就得到Python的浮点表示方法。 #4-timestamp转换为datetime t= 1429417200.0 print(datetime.fromtimestamp(t)) #2015-04-19 12:20:00 #5-str转换为datetime cday = datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S') print(cday) #2015-06-01 18:19:59 #6-datetime转换为str now = datetime.now() print(now.strftime('%a, %b %d %H:%M')) #Mon, May 05 16:28 #7-datetime加减 from datetime import datetime, timedelta now = datetime.now() now + timedelta(days=2, hours=12) #8-本地时间转换为UTC时间
2-collections
#1-namedtuple 命名tuple from collections import namedtuple Point = namedtuple('Point', ['x','y']) p = Point(1,2) print(p.y) #2-deque deque是为了高效实现插入和删除操作的双向列表, from collections import deque q = deque(['a', 'b', 'c']) q.append('x') q.appendleft('y') print(q) #3-defaultdict #使用dict时,如果引用的Key不存在,就会抛出KeyError。 #如果希望key不存在时,返回一个默认值,就可以用defaultdict: from collections import defaultdict dd = defaultdict(lambda: 'N/A') dd['key1'] = 'abc' #4-OrderedDict 按选插入就选输出 from collections import OrderedDict od = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) #5-Counter 统计字符出现的个数: from collections import Counter c = Counter() for ch in 'programming': c[ch] = c[ch] + 1 print(c)