博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python 写的计算指定年指定月日历的脚本
阅读量:7070 次
发布时间:2019-06-28

本文共 4270 字,大约阅读时间需要 14 分钟。

hot3.png

今天初学Python写了一个用于计算指定年指定月日历的脚本

我的Python版本:Python 3.4.2

输入:脚本名 年(4位数字,1900-2100) 月(1-2位数字,1-12)

输出:打印的指定年月日历信息

135439_yuXs_1425762.png

Calendar.py

import osimport sys# check if the number of input is legalif len(sys.argv) != 3:    print('Invalid input! Example: 2014 12')    os.system('pause')  # "press any key to continue..."    os._exit(0)         # terminate this script# check if input(year) is legalprint("Year: %s" % sys.argv[1])if not str(sys.argv[1]).isdigit():    print('Invalid input! Year must be a positive integer')    os.system('pause')     os._exit(0)        elif int(sys.argv[1]) < 1900 or int(sys.argv[1]) > 2100:     print('Invalid input! Year must bigger than 1900 and smaller than 2100')    os.system('pause')     os._exit(0)# check if input(month) is legalprint("Month: %s" % sys.argv[2])if not str(sys.argv[2]).isdigit():    print('Invalid input! Month must be a positive integer')    os.system('pause')     os._exit(0)        elif int(sys.argv[2]) < 1 or int(sys.argv[2]) > 12:     print('Invalid input! Year must bigger than 1 and smaller than 12')    os.system('pause')     os._exit(0)# check: is a leap year or not# param @year: the year input# return: leap: True; not leap: Falsedef IsLeapYear(year):    if year % 4 != 0:        return False    if year % 100 == 0 and year % 400 != 0:        return False    return Truecur_year = sys.argv[1]  # the year inputcur_month = sys.argv[2] # the month input# counter: the first day in cur_year, cur_month, it indicates the day of weekcounter = 0for i in range(1900, int(cur_year)):    if IsLeapYear(i):        counter += 366    else:        counter += 365days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]days_in_month_leap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]for i in range(1, int(cur_month)):    if not IsLeapYear(int(cur_year)):        counter += days_in_month[i - 1]    else:         counter += days_in_month_leap[i - 1]# first_day_in_cur_month: what day is the first day in cur_monthfirst_day_in_cur_month = counter % 7# name of each monthmonth_name = ['January', 'February', 'March', 'April', 'May', 'June', 'July',               'August', 'September', 'October', 'November', 'December']# char numbers of each linecalendar_width = 45# print titleprint()print('=' * calendar_width)space_num = (calendar_width - len(month_name[int(cur_month) - 1])) // 2sys.stdout.write(" "* space_num)sys.stdout.write(month_name[int(cur_month) - 1])sys.stdout.write("\n")print('=' * calendar_width)print("   MON   TUE   WED   THU   FRI   SAT   SUN")print('=' * calendar_width)# establish a calendar# calendar = [[0] * 7] * 6 # can not do like this! change a number then change a columncalendar = [[0, 0, 0, 0, 0, 0, 0],            [0, 0, 0, 0, 0, 0, 0],            [0, 0, 0, 0, 0, 0, 0],            [0, 0, 0, 0, 0, 0, 0],            [0, 0, 0, 0, 0, 0, 0],            [0, 0, 0, 0, 0, 0, 0]]days_count = 0if not IsLeapYear(int(cur_year)):    days_count = days_in_month[int(cur_month) - 1]else:    days_count = days_in_month_leap[int(cur_month) - 1]for i in range(0, days_count):    x = (first_day_in_cur_month + i) // 7    y = (first_day_in_cur_month + i) % 7    calendar[x][y] = i + 1    # print calendarfor i in range(0, 6):        if(i != 0 and calendar[i][0] == 0): # no more days to output then break        break;    sys.stdout.write(" " * 3)    for j in range(0, 7):        str_date = str(calendar[i][j])        sys.stdout.write(" ")        if str_date == "0":            sys.stdout.write("  ")        elif len(str_date) == 1:            sys.stdout.write(str_date)            sys.stdout.write(" ")        else:            sys.stdout.write(str_date)        sys.stdout.write(" " * 3)    sys.stdout.write("\n")# print the end lineprint('=' * calendar_width)print()# os.system('pause')

 

补充说明:使用 Visual Studio 上的 Python 插件时,调试时要设置命令行输入参数,需要进行如下两步

1)项目→Calendar属性(Calendar为项目名)

135724_2D8N_1425762.png

2)在属性界面的Debug选项卡中,设置“Script Arguments”,这个程序的输入为“2014 10”

135724_mDGG_1425762.png

优化:(2014年12月31日)

这3个优化的地方都需要引用calendar,设变量year存储年,变量month存储月

1)遍历一个月的所有天,在本文的代码中,用range(0, days_count),

可以用calendar.monthrange(year, month)代替

2)找出一个月的第一天是星期几,之前用first_day_in_cur_month保存,

可以用calendar.weekday(year, month, 1)代替

calendar.weekday函数中,星期一则返回0,星期二则返回1,以此类推,星期日返回6

3)日历矩阵可以直接用calendar.monthcalendar(year, month)得出

END

转载于:https://my.oschina.net/Tsybius2014/blog/356244

你可能感兴趣的文章
Git常用操作命令
查看>>
正则表达式-断言
查看>>
用git合并分支时,如何保持某些文件不被合并
查看>>
局部代码块、构造代码块、静态代码块
查看>>
聚类分析 ---- K-Means算法
查看>>
C語言最新標準-C11 「轉」
查看>>
SaltStack数据系统-Grains详解
查看>>
课程第三天内容《基础交换 三 》
查看>>
Spring(八):缓存
查看>>
全局函数指针作为模板参数
查看>>
URL access forbidden for unknown reason svn: acces
查看>>
kafka基本命令启动和测试
查看>>
你真的已经搞懂JavaScript了吗?
查看>>
Xmanger4远程桌面Ubuntu 12.04
查看>>
WBS分解
查看>>
Merge into 详细介绍
查看>>
apk签名
查看>>
java 获取图片尺寸及大小
查看>>
Web图表开发工具JFreeChart与ChartDirector使用评测
查看>>
交互设计的KISS原则
查看>>