python生成日历
Posted pwsun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python生成日历相关的知识,希望对你有一定的参考价值。
日历是以1900年1月1日 为基础的 那天的星期1是
# 判断是否是闰年
def rn(i):
# 判断是不是闰年
if (i % 400 == 0) or (i % 4 == 0 and i % 100 != 0):
return True
else:
return False
# 计算总天数
def days(y, m):
# 总年数
leap_year = []
common_year = []
for i in range(1900, y):
if rn(i):
leap_year.append(i)
else:
common_year.append(i)
# 本年之前总天数
y_days = 366*len(leap_year) + 365*len(common_year)
# 本年本月之前总天数
m_days = 0
if m == 1:
m_days = 0
elif m == 2:
m_days = 31
elif m == 3:
if rn(y):
m_days = 60
else:
m_days = 59
elif m == 4:
if rn(y):
m_days = 91
else:
m_days = 90
elif m == 5:
if rn(y):
m_days = 121
else:
m_days = 120
elif m == 6:
if rn(y):
m_days = 151
else:
m_days = 150
elif m == 7:
if rn(y):
m_days = 182
else:
m_days = 181
elif m == 8:
if rn(y):
m_days = 213
else:
m_days = 212
elif m == 9:
if rn(y):
m_days = 244
else:
m_days = 243
elif m == 10:
if rn(y):
m_days = 274
else:
m_days = 273
elif m == 11:
if rn(y):
m_days = 305
else:
m_days = 304
elif m == 12:
if rn(y):
m_days = 335
else:
m_days = 334
all_days = y_days + m_days
return all_days
# 判断本月第一天是星期数
def f_day(all_days):
week = 0
if all_days % 7 == 0:
week = 1
elif all_days % 7 == 1:
week = 2
elif all_days % 7 == 2:
week = 3
elif all_days % 7 == 3:
week = 4
elif all_days % 7 == 4:
week = 5
elif all_days % 7 == 5:
week = 6
elif all_days % 7 == 6:
week = 7
return week
# 判断需要显示月份当月天数
def m_d(y, m):
m_30 = [4, 6, 8, 9, 11]
m_31 = [1, 3, 5, 7, 8, 10, 12]
if rn(y) and m == 2:
m_day = 29
else:
if m in m_31:
m_day = 31
elif m in m_30:
m_day = 30
else:
m_day = 28
return m_day
# 打印日历
def cal(m_day, week):
# 第一行
# print(m_day)
s1 = ‘星期日‘ + 3*‘ ‘ + ‘星期一‘ + 3*‘ ‘ + ‘星期二‘ + 3*‘ ‘ + ‘星期三‘ + 3*‘ ‘ + ‘星期四‘ + 3*‘ ‘ + ‘星期五‘ + 3*‘ ‘ + ‘星期六‘
print(s1)
if week == 7:
for i in range(1, m_day+1):
if i < 10:
s = 2 * ‘ ‘ + str(i) + 4 * ‘ ‘
else:
s = 2 * ‘ ‘ + str(i) + 3 * ‘ ‘
print(s, end=‘‘)
if (i + len(s)) % 7 == 0:
print(‘‘)
else:
# week不是星期日的,需要往后移动week个位置
print(8*week*‘ ‘, end=‘‘)
for i in range(1, m_day+1):
if i < 10:
s = 3 * ‘ ‘ + str(i) + 4 * ‘ ‘
else:
s = 3 * ‘ ‘ + str(i) + 3 * ‘ ‘
print(s, end=‘‘)
if (week + i) % 7 == 0:
print(‘‘)
if __name__ == ‘__main__‘:
y = int(input(‘请输入年份‘))
m = int(input(‘请输入月份‘))
all_days = days(y, m)
week = f_day(all_days)
print(week)
m_day = m_d(y, m)
print(m_day)
cal(m_day, week)
以上是关于python生成日历的主要内容,如果未能解决你的问题,请参考以下文章