Contents
  1. I. Built-in Modules
  2. 1.1 datetime — Date and Time
  3. 1.2 collections — Collections
  4. 1.3 itertools
  5. II. Third-Party Modules
  6. 2.1 Pillow

I. Built-in Modules

1.1 datetime — Date and Time

(1) Importing the Module

from datetime import datetime

If you only use import datetime, you must refer to the full name datetime.datetime

(2) Getting Date and Time

Getting the current date and time

>>> now = datetime.now() # 获取当前datetime
>>> print(now)
2015-05-18 16:28:07.198690

Getting a specified date and time

>>> dt = datetime(2015, 4, 19, 12, 20) # 用指定日期时间创建datetime
>>> print(dt)
2015-04-19 12:20:00

(3) Adding and Subtracting Date and Time

You can add and subtract directly with the + and - operators, but you need to import the timedelta class:

>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2015, 5, 18, 16, 57, 3, 540997)
>>> now + timedelta(hours=10)
datetime.datetime(2015, 5, 19, 2, 57, 3, 540997)
>>> now - timedelta(days=1)
datetime.datetime(2015, 5, 17, 16, 57, 3, 540997)
>>> now + timedelta(days=2, hours=12)
datetime.datetime(2015, 5, 21, 4, 57, 3, 540997)

(4) Time Zone Conversion

Get the current UTC time with utcnow(), then convert it to any time zone:

# 拿到UTC时间,并强制设置时区为UTC+0:00:
>>> utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
>>> print(utc_dt)
2015-05-18 09:05:12.377316+00:00
# astimezone()将转换时区为北京时间:
>>> bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
>>> print(bj_dt)
2015-05-18 17:05:12.377316+08:00
# astimezone()将转换时区为东京时间:
>>> tokyo_dt = utc_dt.astimezone(timezone(timedelta(hours=9)))
>>> print(tokyo_dt)
2015-05-18 18:05:12.377316+09:00

The key to time zone conversion is that when you obtain a datetime, you must know its correct time zone, then forcibly set the time zone as the reference time.

Using a timezone-aware datetime, you can convert to any time zone with the astimezone() method.

(5) Converting Between datetime and timestamp

In computers, time is actually represented by numbers. We call the moment of day 1 of month 1, 1970 00:00:00 UTC+00:00 epoch time, recorded as 0. The current time is the number of seconds relative to epoch time, called a timestamp.

To convert a datetime type to a timestamp, simply call the timestamp() method:

>>> dt = datetime(2015, 4, 19, 12, 20) # 用指定日期时间创建datetime
>>> dt.timestamp() # 把datetime转换为timestamp
1429417200.0

To convert a timestamp to a datetime, use datetime’s fromtimestamp() method:

>>> from datetime import datetime
>>> t = 1429417200.0
>>> print(datetime.fromtimestamp(t))
2015-04-19 12:20:00

(6) Converting Between datetime and str

Often, the date and time entered by the user are strings, and you need to process dates and times.

The conversion is done with datetime.strptime(), which requires a date and time format string:

>>> 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

For detailed format codes, see the Python official documentation

To format a date as a string for display to the user, you need to convert it to str, which is done with strftime()

>>> from datetime import datetime
>>> now = datetime.now()
>>> print(now.strftime('%a, %b %d %H:%M'))
Mon, May 05 16:28

1.2 collections — Collections

(1) namedtuple

namedtuple is a function that creates a custom tuple object, specifies the number of elements in the tuple, and lets you refer to an element of the tuple by attribute instead of by index.

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

(2) deque

deque is a double-ended queue designed for efficient insert and delete operations, suitable for queues and stacks (as a replacement for list):

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

deque implements list’s append() and pop(), and also supports appendleft() and popleft(), so you can add or remove elements at the head very efficiently.

(3) OrderedDict

When using dict, Keys are unordered. When iterating over a dict, we cannot determine the order of the Keys. If you want to keep the order of the Keys, you can use OrderedDict:

>>> from collections import OrderedDict
>>> d = dict([('a', 1), ('b', 2), ('c', 3)])
>>> d # dict的Key是无序的
{'a': 1, 'c': 3, 'b': 2}
>>> od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
>>> od # OrderedDict的Key是有序的
OrderedDict([('a', 1), ('b', 2), ('c', 3)])

Note that OrderedDict Keys are arranged in insertion order, not sorted by the Keys themselves:

1.3 itertools

Python’s built-in module itertools provides very useful functions for operating on iterable objects.

(1) Infinite Iterators

count() creates an infinite iterator that never stops; you can only exit with Ctrl+C:

>>> import itertools
>>> natuals = itertools.count(1)
>>> for n in natuals:
...     print(n)
...
1
2
3
...

cycle() infinitely repeats the sequence passed in, and likewise never stops. Note that a string is also a sequence:

>>> import itertools
>>> cs = itertools.cycle('ABC') # 注意字符串也是序列的一种
>>> for c in cs:
...     print(c)
...
'A'
'B'
'C'
'A'
'B'
'C'
...

repeat() infinitely repeats a single element, but if you provide a second argument you can limit the number of repetitions:

>>> ns = itertools.repeat('A', 3)
>>> for n in ns:
...     print(n)
...
A
A
A

(2) Finite Iteration

The takewhile() function returns a finite sequence while the condition holds:

>>> 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() can concatenate a group of iterable objects into a larger iterator:

>>> for c in itertools.chain('ABC', 'XYZ'):
...     print(c)
# 迭代效果:'A' 'B' 'C' 'X' 'Y' 'Z'

groupby() picks out adjacent duplicate elements in an iterator and groups them together:

>>> for key, group in itertools.groupby('AAABBBCCAAA'):
...     print(key, list(group))
...
A ['A', 'A', 'A']
B ['B', 'B', 'B']
C ['C', 'C']
A ['A', 'A', 'A']

II. Third-Party Modules

2.1 Pillow

Pillow is the updated version of PIL. Because PIL only supported Python 2.7 and had long fallen into neglect, a group of volunteers created a compatible version based on PIL, namely Pillow.

Pillow official documentation: https://pillow.readthedocs.org/

(1) Installing Pillow

If you use Anaconda, Pillow is already installed by default. If you set up the Python environment yourself, install it with the following command.

pip install pillow

(2) Image Operations

Importing Pillow

from PIL import Image

Opening an image — JPG file; note the path is the current directory

# 打开一个jpg图像文件,注意是当前路径:
im = Image.open('test.jpg')

Saving an image

# 把缩放后的图像用jpeg格式保存:
im.save('thumbnail.jpg', 'jpeg')

Getting image size

# 获得图像尺寸:
w, h = im.size
print('Original image size: %sx%s' % (w, h))

Resizing an image — scale by half

# 缩放到50%:
im.thumbnail((w//2, h//2))

Blurring an image

# 应用模糊滤镜:
im2 = im.filter(ImageFilter.BLUR)

(3) Drawing

Creating an image

image = Image.new('RGB', (width, height), (255, 255, 255))

Creating a font object

font = ImageFont.truetype('Arial.ttf', 36)

Creating a draw object

draw = ImageDraw.Draw(image)

Filling pixels

draw.point((x, y))

Outputting text

draw.text((x, y), "Text", font=font)

Example: generating a CAPTCHA

from PIL import Image, ImageDraw, ImageFont, ImageFilter

import random

# 随机字母:
def rndChar():
    return chr(random.randint(65, 90))

# 随机颜色1:
def rndColor():
    return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

# 随机颜色2:
def rndColor2():
    return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

# 240 x 60:
width = 60 * 4
height = 60
image = Image.new('RGB', (width, height), (255, 255, 255))
# 创建Font对象:
font = ImageFont.truetype('Arial.ttf', 36)
# 创建Draw对象:
draw = ImageDraw.Draw(image)
# 填充每个像素:
for x in range(width):
    for y in range(height):
        draw.point((x, y), fill=rndColor())
# 输出文字:
for t in range(4):
    draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2())
# 模糊:
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg', 'jpeg')

Pillow