> 文章列表 > Calculating Dates

Calculating Dates

Calculating Dates

Calculating Dates

此案例用calendar模块计算每月特定事件对应的日期。例如,某单位小组会议在每月的第二个星期四召开,计算一年内这个日子,使用monthcalendar() 返回值。

Although the calendar module focuses mostly on printing full calendars in various formats, it also provides functions useful for working with dates in other ways, such as calculating dates for a recurring event. For example, the Python Atlanta Users’ Group meets on the second Thursday of every month. To calculate the dates for the meetings for a year, use the return value of monthcalendar().

To calculate the group meeting dates for a year, assuming they are always on the second Thursday of every month, look at the output of monthcalendar() to find the dates on which Thursday fall. The first and last weeks of the month are padded with 0 values as placeholders for the days falling in the preceding and subsequent months, respectively. For example, if a month starts on a Friday, the value in the first week in the Thursday position will be 0.

The following is the example program’s code:

import calendarimport sysyear = int(sys.argv[1])  # 运行程序时输入的年份参数,转成整型, 在控制台下输入: python 程序名.py year(例如2023)# show every month,
for month in range(1, 13):# Compute the dates for each week that overlaps the month,c = calendar.monthcalendar((year, month))first_week = c[0]second_week = c[1]third_week = c[2]# If there is a Thursday in the first week,# the second Thursday is in the second week.# Otherwise, the second Thursday must be in # the third week.if first_week[calendar.THURSDAY]:meeting_date = second_week[calendar.THURSDAY]else:meeting_date = third_week[calendar.THURSDAY]print('{:>3} {:>2}'.format(calendar.month_abbr[month], meeting_date))

Thus, the meeting schedule for the year is as follows:

D:\\My_Project>python date_time_demo.py 2023
Jan 12
Feb  9
Mar  9
Apr 13
May 11
Jun  8
Jul 13
Aug 10
Sep 14
Oct 12        
Nov  9        
Dec 14        D:\\My_Project>