Python基礎之十二常用內建模組
阿新 • • 發佈:2019-02-07
'''
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'))