csv-to-ics/csv-to-ics.py

90 lines
3.4 KiB
Python
Raw Normal View History

2024-11-17 09:27:52 +01:00
import csv
import os
2024-11-17 19:55:44 +01:00
import uuid
import json
2024-11-17 09:27:52 +01:00
from ics import Calendar, Event
from datetime import datetime
import pytz
2024-11-17 19:55:44 +01:00
UID_STORE_FILE = "event_uids.json"
def load_uids():
"""Load the UID mappings from a JSON file."""
if os.path.exists(UID_STORE_FILE):
with open(UID_STORE_FILE, "r") as file:
return json.load(file)
return {}
def save_uids(uids):
"""Save the UID mappings to a JSON file."""
with open(UID_STORE_FILE, "w") as file:
json.dump(uids, file)
2024-11-17 09:27:52 +01:00
def generate_ical_from_csv(csv_file):
2024-11-17 19:55:44 +01:00
# Load existing UIDs
uids = load_uids()
2024-11-17 09:27:52 +01:00
# Generate the output .ics file name
ical_file = os.path.splitext(csv_file)[0] + '.ics'
# Define CET time zone
2024-11-17 19:55:44 +01:00
cet = pytz.timezone('Europe/Berlin')
2024-11-17 09:27:52 +01:00
# Create a new calendar
calendar = Calendar()
# Read the CSV file
try:
with open(csv_file, mode='r', encoding='utf-8-sig', errors='replace') as file:
reader = csv.DictReader(file, delimiter=';') # Updated to use ';' as the delimiter
for row in reader:
try:
# Parse the data from CSV
host = row['Host']
2024-11-17 09:27:52 +01:00
description = row['Description']
date = row['Date'].strip() # Expected format: DD.MM.YYYY
start_time = row['start time'].strip() # Expected format: HH:MM
end_time = row['end time'].strip() # Expected format: HH:MM
location = row['Location']
# Combine date and time using the updated date format and apply CET
start_datetime = cet.localize(datetime.strptime(f"{date} {start_time}", "%d.%m.%Y %H:%M"))
end_datetime = cet.localize(datetime.strptime(f"{date} {end_time}", "%d.%m.%Y %H:%M"))
2024-11-17 19:55:44 +01:00
# Create a unique key for the event
event_key = f"{description}_{date}_{start_time}_{location}"
# Retrieve or generate a UID
uid = uids.get(event_key, str(uuid.uuid4()))
uids[event_key] = uid
2024-11-17 09:27:52 +01:00
# Create a new event
event = Event()
2024-11-17 19:55:44 +01:00
event.name = f"{description} (Gastgeber: {host})"
2024-11-17 09:27:52 +01:00
event.begin = start_datetime
event.end = end_datetime
event.location = location
2024-11-17 19:55:44 +01:00
event.uid = uid # Set the unique identifier
event.last_modified = datetime.now() # Timestamp for updates
2024-11-17 09:27:52 +01:00
# Add the event to the calendar
calendar.events.add(event)
except Exception as e:
print(f"Error processing row: {row}. Error: {e}")
# Write the calendar to an iCal file
with open(ical_file, mode='w', encoding='utf-8') as file:
file.writelines(calendar)
2024-11-17 19:55:44 +01:00
# Save UIDs for future use
save_uids(uids)
2024-11-17 09:27:52 +01:00
print(f"iCal file created: {ical_file}")
except Exception as e:
print(f"Failed to read CSV file: {csv_file}. Error: {e}")
# Usage Example
if __name__ == "__main__":
# Ask the user for the CSV file
csv_file = input("Enter the path to the CSV file: ").strip()
# Validate the file exists
if not os.path.isfile(csv_file):
print("The specified file does not exist. Please try again.")
else:
generate_ical_from_csv(csv_file)