You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用calendar包的ic_write函数将DataFrame转换为ICS文件?

将DataFrame事件转为可导入的ICS文件

前置准备

安装icalendar库(你提到的ic_write依赖该库):

pip install icalendar

步骤1:预处理DataFrame时间列

确保开始/结束时间为datetime类型,否则先转换:

import pandas as pd
from icalendar import Calendar, Event

# 构建示例DataFrame
df = pd.DataFrame(
    [
        ["2024-03-11 10:00:00", "2024-03-11 11:00:00", "Event1"],
        ["2024-03-13 10:00:00", "2024-03-13 11:00:00", "Event2"],
        ["2024-03-15 10:00:00", "2024-03-15 11:00:00", "Event3"]
    ],
    columns=["start_time", "end_time", "title"]
)

# 转换时间列类型
df["start_time"] = pd.to_datetime(df["start_time"])
df["end_time"] = pd.to_datetime(df["end_time"])

步骤2:创建ical类对象(Calendar实例)

初始化Calendar对象,并遍历DataFrame添加所有事件:

# 创建Calendar主对象
cal = Calendar()
# 添加必要的日历元信息
cal.add('prodid', '-//Custom Event Calendar//EN')
cal.add('version', '2.0')

# 逐个添加事件
for _, row in df.iterrows():
    event = Event()
    event.add('summary', row["title"])
    event.add('dtstart', row["start_time"])
    event.add('dtend', row["end_time"])
    # 添加唯一ID,避免日历导入时重复创建
    event.add('uid', f"{row['title']}_{row['start_time'].timestamp()}@example.com")
    cal.add_component(event)

步骤3:用ic_write生成ICS文件

如果你的ic_write是封装好的写入函数,直接传入Calendar对象即可:

ic_write(cal, filename='my_events.ics')

如果使用icalendar原生方法,直接写入文件:

with open('my_events.ics', 'wb') as f:
    f.write(cal.to_ical())

生成的my_events.ics可直接导入Outlook、Google日历、苹果日历等应用。

内容的提问来源于stack exchange,提问作者Lily

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 21:24:53