|
目录自定义日历库常用列表日期列表常用函数闰年判断月份天数元旦序号日历表头星期序号序号及天数月历字串打印月历年历字串打印年历对比测试测试结果完整代码运行结果自定义日历库自定义日历库函数,并使得其与pythoncalendar库中对应的函数功能基本一致。常用列表month_name=['January','February','March','April','May','June','July', 'August','September','October','November','December']day_name=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']defdaylist(year,month): days=['']*weekday(year,month)+[*range(1,monthday(year)[month-1]+1)] returndays+['']*(42-len(days))defdayslist(year,month): dlist,count=daylist(year,month),monthday(year)[month-1]//7+2 mlist=[''.join(map(lambdan:str(n).rjust(2),dlist[i*7:i*7+7]))foriinrange(count)] return[month_name[month-1].center(20),weekheader(),*mlist]常用函数为方便写代码间隔都以库函数默认值为准,放弃对库函数的间隔参数进行模拟,比如:calendar.prcal(theyear,w=0,l=0,c=6,m=3),其中 w,l,c为间隔参数。闰年判断判断条件:年份数能被4整除且不能被100整除,或者能被400整除的defisleap(year): '''ReturnTrueforleapyears,Falsefornon-leapyears.''' returnyear%4==0andyear%100!=0oryear%400==0月份天数12个月份的天数,只有2月份的天数是可变的,闰年+1。monthday=lambdayear:[31,28+isleap(year),31,30,31,30,31,31,30,31,30,31]元旦序号这个计算公式看似很神奇,实际上它的本质也就来源于闰年判断公式isleap(year)。即计算公元1年到给定年份(不包括)之间有多少个年份是闰年,公元1年1月1日是星期一是计算基准。所以年份数减一加上能被4整除的年数减去那些能被100整除但不能被400整除的年数加上能被400整除的年数即周一的总位移数,这个结果取余(%7)后的结果0-6对应的是周一~周日。firstday=lambdayearyear-1+(year-1)//4-(year-1)//100+(year-1)//400)%7使用python3.8及以上的版本,有个海象操作符,上式改写成以下形式:firstday=lambdayeary+y//4-y//100+y//400)%7if(y:=year-1)+1elseNone是不是更简洁了,顺便还去掉了0年,因为年份只有公元1年公元前1年,中间没有公元0年的。日历表头defweekheader(width=2): '''Returnaheaderforaweek.''' space=((width-2ifwidth>3else1)*'') returnspace.join(map(lambdax:x[:min(width,3)ifwidth>>importcalendar,mycalendar>>>all((calendar.weekday(i,1,1)==mycalendar.weekday(i,1,1)foriinrange(3000)))True>>>all((calendar.monthrange(i,1)==mycalendar.monthrange(i,1)foriinrange(3000)))True>>>all((calendar.month(i,1)==mycalendar.month(i,1)foriinrange(3000)))True>>>all((calendar.calendar(i)==mycalendar.calendar(i)foriinrange(3000)))True#测试结果:四个主要函数的运行结果在3000年中与对应库函数的完全一致。完整代码month_name=['January','February','March','April','May','June','July','August','September','October','November','December']day_name=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']defdaylist(year,month):days=['']*weekday(year,month)+[*range(1,monthday(year)[month-1]+1)]returndays+['']*(42-len(days))defdayslist(year,month):dlist,count=daylist(year,month),monthday(year)[month-1]//7+2mlist=[''.join(map(lambdan:str(n).rjust(2),dlist[i*7:i*7+7]))foriinrange(count)]return[month_name[month-1].center(20),weekheader(),*mlist]defisleap(year):'''ReturnTrueforleapyears,Falsefornon-leapyears.'''returnyear%4==0andyear%100!=0oryear%400==0monthday=lambdayear:[31,28+isleap(year),31,30,31,30,31,31,30,31,30,31]firstday=lambdayearyear-1+(year-1)//4-(year-1)//100+(year-1)//400)%7defweekheader(width=2):'''Returnaheaderforaweek.'''space=((width-2ifwidth>3else1)*'')returnspace.join(map(lambdax:x[:min(width,3)ifwidth
|
|