编程实现在日历上标记重要节假日
时间: 2024-03-10 15:19:24 浏览: 128
实现这个功能可以使用Python中的`calendar`和`datetime`模块。具体步骤如下:
1. 导入`calendar`和`datetime`模块:
```python
import calendar
from datetime import date
```
2. 创建一个`Calendar`对象,并指定每周的第一天为周一:
```python
c = calendar.Calendar(firstweekday=calendar.MONDAY)
```
3. 获取当前年份:
```python
year = date.today().year
```
4. 定义一个存储重要节假日日期的字典`holidays`,以及对应的标记符号`marks`:
```python
holidays = {
date(year, 1, 1): "元旦节",
date(year, 2, 12): "春节",
date(year, 4, 4): "清明节",
date(year, 5, 1): "劳动节",
date(year, 6, 14): "端午节",
date(year, 9, 21): "中秋节",
date(year, 10, 1): "国庆节"
}
marks = ["*", "+", "-", "#", "^", "&", "@"]
```
5. 遍历每个月,获取每个月的第一天和最后一天,然后遍历该月每一天,如果该天是重要节假日,则在日历上标记:
```python
for month in range(1, 13):
# 获取该月第一天和最后一天
_, last_day = calendar.monthrange(year, month)
first_date = date(year, month, 1)
last_date = date(year, month, last_day)
# 遍历该月每一天
for d in c.itermonthdates(year, month):
if d.month != month: # 如果不是该月的日期则跳过
continue
if d in holidays: # 如果是重要节假日则在日历上标记
mark = marks[list(holidays.keys()).index(d) % len(marks)]
print(f"{d.month}/{d.day:>2}{mark:<2}", end=" ")
else:
print(f"{d.month}/{d.day:>2} ", end=" ")
if d == last_date: # 如果是该月最后一天则换行
print()
```
完整代码如下:
```python
import calendar
from datetime import date
c = calendar.Calendar(firstweekday=calendar.MONDAY)
year = date.today().year
holidays = {
date(year, 1, 1): "元旦节",
date(year, 2, 12): "春节",
date(year, 4, 4): "清明节",
date(year, 5, 1): "劳动节",
date(year, 6, 14): "端午节",
date(year, 9, 21): "中秋节",
date(year, 10, 1): "国庆节"
}
marks = ["*", "+", "-", "#", "^", "&", "@"]
for month in range(1, 13):
_, last_day = calendar.monthrange(year, month)
first_date = date(year, month, 1)
last_date = date(year, month, last_day)
for d in c.itermonthdates(year, month):
if d.month != month:
continue
if d in holidays:
mark = marks[list(holidays.keys()).index(d) % len(marks)]
print(f"{d.month}/{d.day:>2}{mark:<2}", end=" ")
else:
print(f"{d.month}/{d.day:>2} ", end=" ")
if d == last_date:
print()
```
阅读全文