import datetime
# 假设这是一个包含历史天气数据的字典,键为日期,值为温度
historical_weather_data = {
"2023-04-01": 25,
"2023-04-02": 23,
"2023-04-03": 27,
"2023-04-04": 24,
"2023-04-05": 22,
"2023-04-06": 20,
"2023-04-07": 21,
"2023-04-08": 26,
"2023-04-09": 19,
"2023-04-10": 18,
"2023-04-11": 22,
"2023-04-12": 20,
"2023-04-13": 19,
"2023-04-14": 24,
"2023-04-15": 25,
"2023-04-16": 23,
"2023-04-17": 21,
"2023-04-18": 18,
"2023-04-19": 19,
"2023-04-20": 20,
"2023-04-21": 22,
"2023-04-22": 25,
"2023-04-23": 23,
"2023-04-24": 24,
"2023-04-25": 26,
"2023-04-26": 19,
"2023-04-27": 21,
"2023-04-28": 22,
"2023-04-29": 20,
"2023-04-30": 18,
}
def get_weather_for_month(year, month):
# 获取指定月份的第一天和最后一天
first_day = datetime.date(year, month, 1)
last_day = datetime.date(year, month + 1, 1) - datetime.timedelta(days=1)
# 存储该月每天的天气信息
weather_info = {}
# 遍历所有日期,如果日期在指定月份内,则获取天气信息
for date_str, temperature in historical_weather_data.items():
date = datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
if first_day <= date <= last_day:
weather_info[datetime.date.strftime(date, "%d")] = temperature
return weather_info
# 使用示例
year = 2023
month = 4
weather_for_month = get_weather_for_month(year, month)
# 打印该月的天气信息
print(f"在{year}年{month}月的天气情况如下:")
for day, temperature in weather_for_month.items():
print(f"{day}日: 温度为 {temperature}°C")
这段代码定义了一个函数 get_weather_for_month,它接受年份和月份作为参数,并返回一个字典,该字典包含该月每天的天气信息。这里使用了一个假设的历史天气数据字典 historical_weather_data 来模拟实际数据。函数首先确定该月的第一天和最后一天,然后遍历所有日期,如果日期在指定月份内,则从假设的历史数据中提取相应的天气信息。
请注意,这个示例中的天气数据是硬编码的,实际应用中,你可能需要从外部数据源(如天气API)获取实时天气数据。此外,这个脚本只考虑了温度信息,实际应用中可能需要更详细的天气信息,如湿度、风速等。
