Python调用AppleScript添加日历事件报错:Failed to save event
解决macOS日历AppleScript添加事件时结束日期未识别的问题
问题分析
你遇到的报错核心原因是:AppleScript的date命令无法正确解析YYYY-MM-DDTHH:MM:SS这种带"T"的ISO格式字符串。虽然开始日期看似正常,实际是系统解析的巧合,结束日期的解析失败直接导致日历判定未设置结束日期。
解决方案
方案1:修改日期格式(最直接)
将日期字符串中的"T"替换为空格,转换成AppleScript能稳定识别的YYYY-MM-DD HH:MM:SS格式:
import subprocess def addEventToCalendar(start, end, title): # 替换ISO格式中的"T"为空格 start_formatted = start.replace("T", " ") end_formatted = end.replace("T", " ") applescript = f""" tell application "Calendar" set newEvent to make new event at end of events of calendar "Antoine M" set start date of newEvent to date "{start_formatted}" set end date of newEvent to date "{end_formatted}" set description of newEvent to "{title}" end tell """ subprocess.run(['osascript', '-e', applescript], check=True) # 示例调用 addEventToCalendar("2023-11-29T09:00:00", "2023-11-29T10:00:00", "Sample Meeting")
方案2:创建事件时直接指定属性(更可靠)
在make new event时通过with properties直接传入所有属性,避免分步设置可能的顺序问题:
import subprocess def addEventToCalendar(start, end, title): start_formatted = start.replace("T", " ") end_formatted = end.replace("T", " ") applescript = f""" tell application "Calendar" set targetCalendar to calendar "Antoine M" make new event at end of events of targetCalendar with properties {{ start date: date "{start_formatted}", end date: date "{end_formatted}", description: "{title}" }} end tell """ subprocess.run(['osascript', '-e', applescript], check=True)
排查思路
- 单独验证AppleScript日期解析:打开Mac自带的「脚本编辑器」,输入
date "2023-11-29T10:00:00"执行,会发现无法正确解析;换成date "2023-11-29 10:00:00"则能正常返回日期对象。 - 确认日历名称准确性:确保代码中的
"Antoine M"与日历App中显示的名称完全一致(大小写、空格都要匹配)。 - 检查系统日期格式设置:如果替换空格后仍有问题,可以在「系统设置-通用-语言与地区」中查看当前日期时间格式,调整代码中的格式与之匹配。
内容的提问来源于stack exchange,提问作者Antoine Mura
相关产品推荐
相关产品推荐

