Python中的Calendar模块具有Calendar类,该类允许基于日期,月份和年份来计算各种任务。 最重要的是,Python中的TextCalendar和HTMLCalendar类允许您编辑日历并根据需要使用。
让我们看看如何使用Python日历。
步骤1)运行代码。
让我们快速将值从周日更改为周四并检查输出
第2步)您还可以将HTML格式的日历打印出来,如果开发人员希望对日历的外观和风格进行任何更改,此函数对开发人员很有帮助
步骤3)使用c.itermonthday(2025,4)在一个月的天中循环,它将获取该月的总天数。
步骤4)您可以从本地系统中获取数据,例如月份或工作日等
步骤5)您可以获取全年特定日期的列表。 例如,一周的每个第一个星期一都有一个审核日。 您想知道每个月的第一个星期一的日期。 您可以使用此代码
这是完整的代码
Python 2 Example
import calendar
# Create a plain text calendar
c = calendar.TextCalendar(calendar.THURSDAY)
str = c.formatmonth(2025, 1, 0, 0)
print str
# Create an HTML formatted calendar
hc = calendar.HTMLCalendar(calendar.THURSDAY)
str = hc.formatmonth(2025, 1)
print str
# loop over the days of a month
# zeroes indicate that the day of the week is in a next month or overlapping month
for i in c.itermonthdays(2025, 4):
print i
# The calendar can give info based on local such a names of days and months (full and abbreviated forms)
for name in calendar.month_name:
print name
for day in calendar.day_name:
print day
# calculate days based on a rule: For instance an audit day on the second Monday of every month
# Figure out what days that would be for each month, we can use the script as shown here
for month in range(1, 13):
# It retrieves a list of weeks that represent the month
mycal = calendar.monthcalendar(2025, month)
# The first MONDAY has to be within the first two weeks
week1 = mycal[0]
week2 = mycal[1]
if week1[calendar.MONDAY] != 0:
auditday = week1[calendar.MONDAY]
else:
# if the first MONDAY isn't in the first week, it must be in the second week
auditday = week2[calendar.MONDAY]
print "%10s %2d" % (calendar.month_name[month], auditday)
Python 3 Example
import calendar
# Create a plain text calendar
c = calendar.TextCalendar(calendar.THURSDAY)
str = c.formatmonth(2025, 1, 0, 0)
print(str)
# Create an HTML formatted calendar
hc = calendar.HTMLCalendar(calendar.THURSDAY)
str = hc.formatmonth(2025, 1)
print(str)
# loop over the days of a month
# zeroes indicate that the day of the week is in a next month or overlapping month
for i in c.itermonthdays(2025, 4):
print(i)
# The calendar can give info based on local such a names of days and months (full and abbreviated forms)
for name in calendar.month_name:
print(name)
for day in calendar.day_name:
print(day)
# calculate days based on a rule: For instance an audit day on the second Monday of every month
# Figure out what days that would be for each month, we can use the script as shown here
for month in range(1, 13):
# It retrieves a list of weeks that represent the month
mycal = calendar.monthcalendar(2025, month)
# The first MONDAY has to be within the first two weeks
week1 = mycal[0]
week2 = mycal[1]
if week1[calendar.MONDAY] != 0:
auditday = week1[calendar.MONDAY]
else:
# if the first MONDAY isn't in the first week, it must be in the second week
auditday = week2[calendar.MONDAY]
print("%10s %2d" % (calendar.month_name[month], auditday))