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()

The following is the example program’s code:

import calendar

import sys

year = 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>
相关文章
|
算法
uva 11549 CALCULATOR CONUNDRUM
题目链接 刘汝佳算法竞赛经典入门训练指南p42
35 0
A. Calculating Function
A. Calculating Function
52 0
Calculating Function
Calculating Function
97 0
Calculating Function
HDU-1012,u Calculate e
HDU-1012,u Calculate e
|
Go
HDOJ 1012 u Calculate e
HDOJ 1012 u Calculate e
114 0
HDOJ 1012 u Calculate e
|
算法
HDOJ 1202 The calculation of GPA
HDOJ 1202 The calculation of GPA
122 0
|
数据可视化
Paraview: Calculate Derivatives of 3-D Unstructured Dataset
关注九天学者微信公众号(扫码关注)第一时间获取技术贴更新! Paraview 是一款基于VTK的、开源的、跨平台的科学数据可视化软件,其三维显示和后处理功能非常强大。
2815 0