Python根据指定日期生成日历

根据给定日期,生成 5*7的日历。自动补齐前面的日期。

含计算日期,计算星期几等函数。生生复习了一遍闰年和星期几计算。记录下留档。

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# _*_ coding:utf-8 _*_
# Author: Onecer <LDH@QQ.COM>
# Date: 7/26/18 10:20 PM


def is_leap_year(year):
"""
判断闰年
:param year:
:return:
"""
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
return True
else:
return False


def get_days_of_month(year, month):
"""
返回一个月有几天
:param year:
:param month:
:return:
"""
if month in (1, 3, 5, 7, 8, 10, 12):
return 31
elif month in (4, 6, 9, 11):
return 30
elif month ==2:
if is_leap_year(year):
return 29
else:
return 28


def get_day(years, months, days):
"""
获取星期几
:param years:
:param months:
:param days:
:return:
"""
num = 0
for year in range(1800, years):
if is_leap_year(year):
num += 366
else:
num += 365

for month in range(1,months):
num += get_days_of_month(years, month)

num += days-1
return (3 + num) % 7


def inc_date(year, month, day, num):
"""
加日期
:param year:
:param month:
:param day:
:param num:
:return:
"""
if num == 0:
week_day = get_day(year, month, day)
return '[{}-{}-{}/{}]'.format(year, month, day, week_day)
else:
for i in range(0,num):
if get_days_of_month(year, month) > day:
day +=1
else:
month += 1
day = 1

if month > 12:
month = 1
year += 1
week_day = get_day(year, month, day)
return '[{}-{}-{}/{}]'.format(year, month, day, week_day)


def repay_date(year, month, day):
week_day = get_day(year, month, day)
if week_day != 0:
if day - week_day == 0:
month = month - 1
if month == 0:
month = 12
year = year - 1
day = get_days_of_month(year, month)
else:
day = day - week_day

count = 0
for x in range (0,5):
str = ''
for y in range(0,7):
str += inc_date(year,month,day,count) + ','
count += 1
print(str)

repay_date(2018,7,26)

关注公众号 尹安灿