Files
interesing_ideas/birthday/generate_calendar.py
2025-09-04 17:53:59 +08:00

79 lines
3.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# generate_calendar.py (修正版)
import json
from ics import Calendar, Event
from ics.alarm import DisplayAlarm # <--- 1. 导入DisplayAlarm
from datetime import datetime, timedelta
import os
DATA_FILE = 'data/birthdays.json' # 我看到你的截图里文件名是 family.json这里同步修改
OUTPUT_FILE = 'family_birthdays.ics'
def main():
"""主函数生成ICS日历文件"""
if not os.path.exists(DATA_FILE):
print(f"错误: 未找到数据文件 '{DATA_FILE}'。请先运行 add_birthday.py 添加数据。")
return
# 你的截图显示的是 family.json, 如果是 add_birthday.py 生成的 birthdays.json, 请改回
with open(DATA_FILE, 'r', encoding='utf-8') as f:
birthdays = json.load(f)
if not birthdays:
print("数据文件中没有生日信息,无法生成日历。")
return
print("--- 日历文件生成程序 ---")
try:
years_to_generate = int(input("你希望为未来多少年的生日创建提醒?(默认10年): ") or "10")
days_before_remind = int(input("希望提前几天提醒?(0=当天, 1=提前1天, 默认1): ") or "1")
except ValueError:
print("输入无效,将使用默认值。")
years_to_generate = 10
days_before_remind = 1
cal = Calendar()
today = datetime.today()
for person in birthdays:
name = person['name']
try:
birth_date = datetime.strptime(person['birthday'], '%Y-%m-%d').date()
except ValueError:
print(f"警告: {name} 的生日格式 '{person['birthday']}' 不正确,已跳过。")
continue
for i in range(years_to_generate):
current_year_birth_date = birth_date.replace(year=today.year + i)
age = current_year_birth_date.year - birth_date.year + 1
event = Event()
event.name = f"{name}{age} 岁生日 🎂"
event.begin = current_year_birth_date
event.make_all_day()
# --- 核心修改部分 ---
# 2. 直接创建 DisplayAlarm 对象
alarm = DisplayAlarm(
trigger=timedelta(days=-days_before_remind, hours=9), # 提前N天的早上9点提醒
display_text=f"别忘了给 {name} 送上生日祝福!" # 新版库中用 display_text
)
# 3. 将提醒添加到事件的 alarms 集合中
event.alarms.append(alarm)
# --- 修改结束 ---
if i == years_to_generate - 1:
# 给事件本身添加描述
event.description = "注意:这是自动生成的最后一个生日提醒,请记得重新生成日历文件。"
cal.events.add(event)
with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
f.writelines(cal)
print(f"\n成功!日历文件 '{OUTPUT_FILE}' 已生成。")
print("现在你可以将这个文件导入到你的手机或电脑日历应用中了。")
if __name__ == "__main__":
main()