欢迎访问宙启技术站
智能推送

如何用Python编写一个简单的日历程序

发布时间:2023-12-04 14:15:36

编写一个简单的日历程序需要使用到Python的datetime模块和calendar模块。datetime模块提供了一种处理日期和时间的方式,而calendar模块则提供了一些日历相关的功能。

下面是一个简单的日历程序的示例代码:

import datetime
import calendar

def display_calendar(year, month):
    # 获取指定年月的第一天
    first_day = datetime.date(year, month, 1)
    # 获取指定年月的日历
    cal = calendar.monthcalendar(year, month)

    # 打印月份和星期的标题
    print('{:^20s}'.format(calendar.month_name[month]))
    print('{:^20s}'.format('Mon Tue Wed Thu Fri Sat Sun'))

    # 打印日期
    for week in cal:
        for day in week:
            # 如果日期为0表示该日期不在该月份范围内
            if day == 0:
                print('{:^4s}'.format(' '), end='')
            else:
                # 如果日期小于10则在前面补充一个空格
                print('{:^4d}'.format(day), end='')
        print()

# 示例使用
year = 2022
month = 12

display_calendar(year, month)

运行上述程序,将显示一个以指定年和月为输入的日历。例如,上述示例代码将显示2022年12月的日历:

       December        
Mon Tue Wed Thu Fri Sat Sun
                1   2   3  
 4   5   6   7   8   9   10 
11  12  13  14  15  16  17 
18  19  20  21  22  23  24 
25  26  27  28  29  30  31 

这个程序使用了datetime模块的date类和calendar模块的monthcalendar函数。首先,我们根据输入的年和月创建了指定年月的第一天的datetime对象。然后,我们使用monthcalendar函数获取了一个二维列表,表示了该月的日历。

接下来,我们使用两层循环来打印日历。外层循环遍历每一周,内层循环遍历每一天。如果某一天为0,则打印一个空格;否则,打印对应的日期。

这个简单的日历程序只显示一个月的日历,你可以根据需求进行扩展,比如显示一年的日历、添加用户交互等。

希望这个示例代码对你有帮助!