Python万年历系统:生成任意年份和月份的日历
Python万年历系统:生成任意年份和月份的日历
本程序使用Python语言编写一个万年历系统,可以根据用户输入的年份和月份生成日历。功能包括:
- 能够判断闰年并处理闰年情况
- 按照日历格式自动显示7位数,超过7天则自动换行
- 能够自动获取系统时间,显示当前月份的日历
- 具有较强的容错能力,例如输入错误的月份号会提示错误
代码实现
import time
# 判断某年是否是闰年
def is_leap_year(year):
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
return True
else:
return False
# 获取某年某月的天数
def get_days_of_month(year, month):
if month in (1, 3, 5, 7, 8, 10, 12):
return 31
elif month == 2:
if is_leap_year(year):
return 29
else:
return 28
else:
return 30
# 打印某年某月的日历
def print_calendar(year, month):
days_of_month = get_days_of_month(year, month)
# 获取该月1号是周几
first_day = time.strptime('%d-%d-01' % (year, month), '%Y-%m-%d').tm_wday
print('
%d年%d月' % (year, month))
print('日 一 二 三 四 五 六')
for i in range(first_day):
print(' ', end='')
for i in range(1, days_of_month + 1):
print('%2d ' % i, end='')
if (i + first_day) % 7 == 0:
print()
print()
# 获取当前时间所在的年份和月份
current_time = time.localtime()
current_year = current_time.tm_year
current_month = current_time.tm_mon
# 显示当前时间所在的月份的日历
print_calendar(current_year, current_month)
# 输入年份和月份,显示该年月的日历
year = int(input('请输入年份:'))
month = int(input('请输入月份:'))
if year < 0 or month < 1 or month > 12:
print('输入有误!')
else:
print_calendar(year, month)
代码分析
-
is_leap_year函数:- 用于判断某年是否是闰年。
- 根据闰年定义,能够被4整除但不能被100整除,或者能够被400整除的年份都是闰年。
-
get_days_of_month函数:- 用于获取某年某月的天数。
- 根据每个月的天数和闰年的情况来计算。
-
print_calendar函数:- 用于打印某年某月的日历。
- 首先获取该月1号是周几,然后按照日历格式打印出来。
- 通过
if语句实现每行显示7位数,超过则自动换行。
-
获取当前时间:
- 使用
time模块获取当前时间所在的年份和月份。 - 调用
print_calendar函数来显示当前时间所在的月份的日历。
- 使用
-
用户输入:
- 用户输入年份和月份。
- 对输入进行容错处理,确保输入有效。
- 调用
print_calendar函数来显示该年月的日历。
原文地址: https://www.cveoy.top/t/topic/oR8d 著作权归作者所有。请勿转载和采集!