编写一个python万年历带有节日和节气
时间: 2023-06-03 07:03:15 浏览: 301
好的,我可以回答这个问题。以下是一个简单的Python万年历代码,包含节日和节气:
```python
import calendar
import datetime
import requests
import json
def get_lunar_date(year, month, day):
url = f"http://api.xlongwei.com/service/datetime/convert.json?d={year}-{month}-{day}T00:00:00"
response = requests.get(url)
data = json.loads(response.text)
lunar_year = data["lunarYear"]
lunar_month = data["lunarMonth"]
lunar_day = data["lunarDay"]
lunar_date = f"{lunar_year}年{lunar_month}月{lunar_day}"
return lunar_date
def print_calendar(year, month):
cal = calendar.monthcalendar(year, month)
for week in cal:
for day in week:
if day == 0:
print(" ", end="")
else:
today = datetime.date(year, month, day)
lunar_date = get_lunar_date(year, month, day)
print(f"{day:^2}({lunar_date:<2})", end="")
festivals = get_festivals(today)
if festivals:
print(" " + festivals, end="")
solar_terms = get_solar_terms(today)
if solar_terms:
print(" " + solar_terms, end="")
print(" ", end="")
print()
def get_festivals(date):
festivals = {"0101": "元旦节",
"0401": "愚人节",
"0501": "劳动节",
"0601": "儿童节",
"1001": "国庆节",
"1224": "平安夜",
"1225": "圣诞节"}
month = f"{date.month:02d}"
day = f"{date.day:02d}"
date_str = month + day
return festivals.get(date_str)
def get_solar_terms(date):
url = f"http://www.sojson.com/api/lunar/solar-term/{date.year}"
response = requests.get(url)
data = json.loads(response.text)
solar_terms = data.get(str(date.month)).get(str(date.day))
return solar_terms
if __name__ == "__main__":
today = datetime.date.today()
year = input("请输入年份: ") or today.year
month = input("请输入月份: ") or today.month
year = int(year)
month = int(month)
print(f"{year}年{month}月日历")
print("-" * 40)
print("日 一 二 三 四 五 六 ")
print("-" * 40)
print_calendar(year, month)
```
这个万年历代码使用了Python内置的calendar模块来生成日历,并使用了第三方API获取农历信息和节气信息。代码中的get_festivals函数可以返回节日名称,get_solar_terms函数可以返回节气名称。可以根据需要修改或添加节日和节气。
阅读全文