Python基础之十二常用內建模块

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014360817/article/details/54844756
'''

    datetime
        datetime是Python处理日期和时间的标准库

'''

###########################获取当前日期和时间
from datetime import datetime
now = datetime.now()#获取当前datetime
print(now)
print(type(now))

###########################获取指定日期和时间
dt = datetime(2015, 4, 19,12, 30)#用指定日期穿件datetime
print(dt)

###########################datetime转换为timestamp
print(dt.timestamp())#把datetime转换为timestamp

###########################timestamp转换为datetime
t = 12343534.0
print(datetime.fromtimestamp(t))
print(datetime.utcfromtimestamp(t))

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

###########################datetime转换为str
now = datetime.now()
print(now.strftime('%a, %b %d %H:%M'))

'''
    collections
        collections是Python内建一个集合模块,提供了许多有用的集合类

'''

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

###########################deque
from  collections import deque
q = deque(['a', 'b', 'c'])
q.append('x')
q.append('y')
print(q)

###########################defaultdict返回默认值
from collections import defaultdict
dd = defaultdict(lambda : 'N/A')
dd['key1'] = 'abc'
print(dd['key1'])
print(dd['key2'])

###########################OrderdDict保证dict顺序

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

###########################Counter简单计数器
from collections import Counter
c = Counter()
for ch in 'programming':
    c[ch] = c[ch] +1
print(c)

'''
    urllib
        urllib提供一系列用于操作URL的功能
'''

###########################Get
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'))

更多精彩内容访问个人站点www.gaocaishun.cn

猜你喜欢

转载自blog.csdn.net/u014360817/article/details/54844756