Advertisement
cosjef

Untitled

Dec 16th, 2024
146
0
24 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.86 KB | None | 0 0
  1. """
  2. Calendar Event Generator
  3. -----------------------
  4.  
  5. This script generates random calendar events and saves them as an .ics file that can be imported
  6. into any calendar application (Apple Calendar, Google Calendar, Outlook, etc.).
  7.  
  8. Dependencies:
  9.    - Python 3.6+
  10.    - icalendar library (install with: pip install icalendar)
  11.  
  12. To run:
  13.    1. Install dependencies:
  14.       pip install icalendar
  15.  
  16.    2. Run the script:
  17.       python calendar_generator.py
  18.  
  19.    3. Find the generated 'random_events.ics' file in your Downloads folder
  20.    
  21.    4. Import the .ics file into your calendar application:
  22.       - Apple Calendar: File -> Import
  23.       - Google Calendar: Settings -> Import & Export -> Import
  24.       - Outlook: File -> Import/Export -> Import an iCalendar file
  25.  
  26. Features:
  27.    - Generates 1-4 events per weekday (weighted random distribution)
  28.    - Includes one "Focus Time" block per day
  29.    - Avoids scheduling conflicts
  30.    - Skips weekends
  31.    - Sets 15-minute reminders for all events
  32.    - Creates events only during business hours (9 AM - 5 PM)
  33.    - Varies meeting durations between 30-90 minutes
  34.    - Customizable meeting subjects (edit the list in get_random_name() function)
  35.  
  36. Author: [Your name here]
  37. Date: [Current date]
  38. """
  39.  
  40. from datetime import datetime, timedelta
  41. import random
  42. from icalendar import Calendar, Event
  43. import uuid
  44. import os
  45. from pathlib import Path
  46.  
  47. def create_calendar_event(calendar, subject, start_time, end_time):
  48.     """Create a calendar event and add it to the calendar."""
  49.     event = Event()
  50.     event.add('summary', subject)
  51.     event.add('dtstart', start_time)
  52.     event.add('dtend', end_time)
  53.    
  54.     # Add reminder (15 minutes before)
  55.     from icalendar import Alarm
  56.     alarm = Alarm()
  57.     alarm.add('action', 'DISPLAY')
  58.     alarm.add('trigger', timedelta(minutes=-15))
  59.     alarm.add('description', subject)
  60.     event.add_component(alarm)
  61.    
  62.     # Add unique identifier
  63.     event['uid'] = str(uuid.uuid4())
  64.    
  65.     # Add status and transparency
  66.     event.add('status', 'CONFIRMED')
  67.     event.add('transp', 'OPAQUE')  # Marks as busy
  68.    
  69.     calendar.add_component(event)
  70.     print(f"Event created: {subject} from {start_time} to {end_time}")
  71.  
  72. def get_random_name():
  73.     """Generate a random meeting subject."""
  74.     subjects = [
  75.         "Project Review", "Client Follow-Up", "Performance Update",
  76.         "Strategic Planning", "Budget Discussion", "Sprint Retrospective",
  77.         "Operational Review", "Focus Time", "Priority Planning",
  78.         "KPI Review", "Status Update", "Market Analysis",
  79.         "Content Review", "Department Check-In", "Stakeholder Meeting",
  80.         "Report Drafting", "Goal Setting", "Next Steps Planning",
  81.         "Annual Planning", "Feedback Session", "Weekly Review",
  82.         "Risk Management", "Results Presentation", "Roadmap Planning"
  83.     ]
  84.     return random.choice(subjects)
  85.  
  86. def get_random_events_count():
  87.     """Generate a random number of events for a day."""
  88.     # Weights for number of daily events:
  89.     # 1 event:  10% chance
  90.     # 2 events: 45% chance
  91.     # 3 events: 25% chance
  92.     # 4 events: 20% chance
  93.     weights = [10, 45, 25, 20]  # Weights for 1-4 events
  94.     return random.choices(range(1, 5), weights=weights)[0]
  95.  
  96. def check_for_conflicts(events, start_time, end_time):
  97.     """Check if there are any conflicts with existing events."""
  98.     for event in events:
  99.         event_start = event.get('dtstart').dt
  100.         event_end = event.get('dtend').dt
  101.         if (start_time < event_end and end_time > event_start):
  102.             return True
  103.     return False
  104.  
  105. def generate_random_events(days=5):
  106.     """Generate random calendar events for the specified number of days."""
  107.     # Create a new calendar
  108.     cal = Calendar()
  109.     cal.add('prodid', '-//Random Calendar Generator//example.com//')
  110.     cal.add('version', '2.0')
  111.    
  112.     # Keep track of all events for conflict checking
  113.     all_events = []
  114.    
  115.     now = datetime.now()
  116.     now = now.replace(hour=0, minute=0, second=0, microsecond=0)
  117.    
  118.     for i in range(days):
  119.         day_date = now + timedelta(days=i)
  120.        
  121.         # Skip weekends
  122.         if day_date.strftime('%A') in ['Saturday', 'Sunday']:
  123.             continue
  124.            
  125.         # Randomly determine number of events for this day
  126.         events_for_today = get_random_events_count()
  127.         print(f"\nGenerating {events_for_today} events for {day_date.strftime('%A, %B %d')}")
  128.        
  129.         generated_events = 0
  130.         focus_time_created = False
  131.         attempts = 0  # Add a maximum attempts counter to prevent infinite loops
  132.        
  133.         while generated_events < events_for_today and attempts < 50:  # Limit attempts
  134.             attempts += 1
  135.            
  136.             # Randomly choose morning or afternoon
  137.             if random.choice(['Morning', 'Afternoon']) == 'Morning':
  138.                 start_hour = random.randint(9, 11)  # Extended morning hours
  139.             else:
  140.                 start_hour = random.randint(13, 16)  # Extended afternoon hours
  141.                
  142.             start_minute = random.choice([0, 15, 30, 45])
  143.             duration = random.randint(30, 90)  # More flexible duration
  144.            
  145.             # Create datetime objects for start and end times
  146.             start_time = day_date.replace(hour=start_hour, minute=start_minute)
  147.             end_time = start_time + timedelta(minutes=duration)
  148.            
  149.             # Check if the meeting would end after 5 PM
  150.             if end_time.hour >= 17:
  151.                 continue
  152.            
  153.             if not check_for_conflicts(all_events, start_time, end_time):
  154.                 # Determine subject (ensure one Focus Time per day)
  155.                 if not focus_time_created:
  156.                     subject = "Focus Time"
  157.                     focus_time_created = True
  158.                 else:
  159.                     subject = get_random_name()
  160.                
  161.                 # Create the event
  162.                 event = Event()
  163.                 event.add('summary', subject)
  164.                 event.add('dtstart', start_time)
  165.                 event.add('dtend', end_time)
  166.                 event['uid'] = str(uuid.uuid4())
  167.                
  168.                 all_events.append(event)
  169.                 create_calendar_event(cal, subject, start_time, end_time)
  170.                 generated_events += 1
  171.    
  172.     # Save to file
  173.     output_dir = Path.home() / "Downloads"
  174.     output_file = output_dir / "random_events.ics"
  175.    
  176.     with open(output_file, 'wb') as f:
  177.         f.write(cal.to_ical())
  178.    
  179.     print(f"\nCalendar file has been created at: {output_file}")
  180.     print("You can import this file into Apple Calendar or any other calendar application.")
  181.  
  182. if __name__ == "__main__":
  183.     try:
  184.         generate_random_events()
  185.         print("Calendar events generation completed successfully!")
  186.     except Exception as e:
  187.         print(f"An error occurred: {str(e)}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement