logo头像
Snippet 博客主题

Python3 - 打印月历

Python封装了许多强大的模块, 通过调用模块, 可以让复杂的代码简单化, 今天我们来介绍两种打印月历的方法

一、使用python模块打印月份日历

1
2
3
4
import calendar # 导入日历模块

month = calendar.month(2018, 5)
print(month)

输出结果

1
2
3
4
5
6
7
     May 2018
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31

二、封装函数打印月份日历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def is_leap_year(year):
# 判断是否为闰年
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
return True
else:
return False


def get_month_days(year, month):
# 给定年月返回月份的天数
if month in (1, 3, 5, 7, 8, 10, 12):
return 31
elif month in (4, 6, 9, 11):
return 30
elif is_leap_year(year):
return 29
else:
return 28


def get_start_day(year, month):
# 返回当月1日是星期几
# c:世纪
# y:年(后两位数)
c, y = int(str(year)[:2]), int(str(year)[2:])
# 使用蔡勒函数返回当月1日是星期几
if month == 1 or month == 2:
return (y - 1 + (y - 1) // 4 + c // 4 - 2 * c + 26 * (
month + 12 + 1) // 10 + 1 - 1) % 7
else:
return (y + y // 4 + c // 4 - 2 * c + 26 * (month + 1) // 10 + 1 - 1) % 7


# 月份与名称对应的字典
month_dict = {1: 'January', 2: 'February', 3: 'March', 4: 'April',
5: 'May', 6: 'June', 7: 'July', 8: 'August',
9: 'September', 10: 'October', 11: 'November', 12: 'December'}


def get_title(year, month):
# 打印日历的首部
print(' ', month_dict[month], year)
print('Su Mo Tu We Th Fr Sa')


def print_month(year, month):
i = get_start_day(year, month) % 7
if i != 7:
print(' ' * i, end='') # 从星期几开始则空5*i个空格
for j in range(1, get_month_days(year, month) + 1):
print('%2d' % j, end=' ') # 宽度控制
i += 1
if i % 7 == 0: # i用于计数和换行
print()


if __name__ == '__main__':
year = 2018
month = 5
get_title(year, month)
print_month(year, month)

输出结果

1
2
3
4
5
6
7
      May 2018
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

评论系统未开启,无法评论!