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

使用Python自动生成日历

发布时间:2023-12-11 03:27:16

Python中有一个内置的日历模块,可以用于生成日历并进行相关的日期操作。下面是使用Python自动生成日历的示例代码:

import calendar

# 打印某年某月的日历
def print_calendar(year, month):
    cal = calendar.monthcalendar(year, month)
    for week in cal:
        print(week)

# 判断某年是否是闰年
def is_leap_year(year):
    return calendar.isleap(year)

# 获取某年某月的      天是星期几
def get_first_weekday(year, month):
    _, first_weekday = calendar.monthrange(year, month)
    return first_weekday

# 打印当前月份的日历
def print_current_month_calendar():
    import datetime
    now = datetime.datetime.now()
    year, month = now.year, now.month
    print_calendar(year, month)

# 打印当前年份的日历
def print_current_year_calendar():
    import datetime
    now = datetime.datetime.now()
    year = now.year
    for month in range(1, 13):
        print_calendar(year, month)


# 使用示例
print("打印2022年1月的日历:")
print_calendar(2022, 1)

print("
判断2022年是否是闰年:")
print(is_leap_year(2022))

print("
获取2022年1月的      天是星期几:")
print(get_first_weekday(2022, 1))

print("
打印当前月份的日历:")
print_current_month_calendar()

print("
打印当前年份的日历:")
print_current_year_calendar()

运行上述代码后,会分别输出不同功能的结果。比如打印2022年1月的日历、判断2022年是否是闰年、获取2022年1月的 天是星期几等。同时还有打印当前月份的日历和打印当前年份的日历的示例。

通过使用日历模块,可以方便地生成日历,并进行相关的日期操作。你可以根据自己的需求和具体场景,使用这些功能来完成更多有趣的任务。