1.生成日期
from datetime import datetime, timedelta # 设置开始日期和结束日期 start_date = datetime(2024, 8, 23) end_date = datetime(2024, 10, 30) # 列表用于存储每个周期的最后两天的日期 result_dates = [] current_date = start_date - timedelta(days=1) while current_date <= end_date: # 计算周期结束日期 period_end_date = current_date + timedelta(days=5) # 添加周期的最后两天到结果列表 result_dates.append(period_end_date - timedelta(days=1)) result_dates.append(period_end_date) # 移动到下一个周期的开始日期 current_date = period_end_date + timedelta(days=1) # 打印结果日期列表 for date in result_dates: print(date.strftime("%Y-%m-%d"))
2.保存为csv文件后(设置好列名称),转为ics文件
# Subject, Start Date, End Date
import csv from icalendar import Calendar, Event from datetime import datetime, timedelta import os # 设置CSV文件和ICS文件的路径 csv_file_path = "dating.csv" ics_file_path = "dating.ics" def convert_date(date_str): """将日期字符串从 %Y/%m/%d 格式转换为 %Y-%m-%d 格式""" return datetime.strptime(date_str, "%Y/%m/%d").strftime("%Y-%m-%d") try: # 创建一个新的日历 calendar = Calendar() # 打开并读取CSV文件,处理BOM字符 with open(csv_file_path, newline='', encoding='utf-8') as csvfile: # 读取文件内容 file_content = csvfile.read() # 检查BOM并删除 if file_content.startswith('\ufeff'): file_content = file_content.lstrip('\ufeff') # 使用字符串IO读取去掉BOM后的内容 from io import StringIO csvfile = StringIO(file_content) reader = csv.DictReader(csvfile) # 打印CSV文件的列名 print("CSV文件的列名:", reader.fieldnames) for row in reader: print("读取行:", row) # 打印读取的每一行 event = Event() #event.add('summary', f"{row['Subject']} ❤️") # 在事件标题中添加爱心符号 start_date_str = convert_date(row['Start Date']) end_date_str = convert_date(row['End Date']) start_date = datetime.strptime(start_date_str, "%Y-%m-%d") end_date = datetime.strptime(end_date_str, "%Y-%m-%d") # 设置事件的开始和结束日期 event.add('dtstart', start_date) event.add('dtend', end_date + timedelta(days=1)) # ICS的结束日期是独占的,所以需要加一天 # 将事件添加到日历 calendar.add_component(event) # 将日历写入ICS文件 with open(ics_file_path, 'wb') as my_file: my_file.write(calendar.to_ical()) print("ICS文件已创建") except Exception as e: print(f"出错了:{e}")