def makeClass(calendar, classesStartDate, classesEndDate): startOfSemesterDT = "" endOfSemesterDT = "" startOfSemesterICS = "" endOfSemesterICS = "" if type(classesStartDate) is str: startOfSemesterDT = localTimeToUTC(ICSToDateTime(classesStartDate)) endofSemesterDT = localTimeToUTC(ICSToDateTime(classesEndDate)) startOfSemesterICS = classesStartDate endOfSemesterICS = classesEndDate else: startOfSemesterDT = localTimeToUTC(classesStartDate) endOfSemesterDT = localTimeToUTC(classesEndDate) startOfSemesterICS = dateTimeToICS(localTimeToUTC(classesStartDate)) endOfSemesterICS = dateTimeToICS(localTimeToUTC(classesEndDate)) name = input("What is the class name? ") daysOfClassChars = input("What are the days for the class? (MTWRFSU) ") location = input("Where is the class held? ") professor = input("Who is the professor? ") startTime = input("When does the class start? (HH:MM) ") endTime = input("When does the class end? (HH:MM) ") days = ['M', 'T', 'W', 'R', 'F', 'S', 'U'] weekdayOfStartOfSemester = startOfSemesterDT.weekday() % len(days) weekdayOfStartOfClass = 0 for i in range(weekdayOfStartOfSemester, len(days)): for dayChar in daysOfClassChars: if days[i] is dayChar: weekdayOfStartOfClass = i weekdaysOfClassInts = [] for dayOfClass in daysOfClassChars: for i in range(0, len(days)): if dayOfClass is days[i]: weekdaysOfClassInts.append(i) nextDT = nextWeekday(startOfSemesterDT, weekdayOfStartOfClass) classStart = localTimeToUTC( datetime(nextDT.year, nextDT.month, nextDT.day, hour=int(startTime[:2]), minute=int(startTime[3:]))) classEnd = localTimeToUTC( datetime(classStart.year, classStart.month, classStart.day, hour=int(endTime[:2]), minute=int(endTime[3:]))) allDTs = getAllDTs(classStart, classEnd, endOfSemesterDT, weekdaysOfClassInts) events = [] for dates in allDTs: temp = Event() temp.name = str(name) temp.description = "Professor: " + str(professor) temp.begin = dates[0] temp.end = dates[1] temp.location = str(location) events.append(temp) return events
def generate_ics_calendar(self, filename=''): logger.debug(f"Refreshed ICS for {self.username}") @MemoizeWithTimeout() def format_ics_date(event_date): return get_ade_timezone().localize( datetime.strptime(event_date, '%d/%m/%Y %H:%M')) def format_ics_location(classroom): return f'{classroom["name"]} ({", ".join(classroom["genealogy"])})' def format_geolocation(classrooms): try: # Returns the first geolocation found return next(filter( None, (c.get('geolocation') for c in classrooms)))[:2] except Exception: return None @MemoizeWithTimeout() def format_end_date(dt, offset): return dt + timedelta( minutes=(int(offset) * settings.ADE_DEFAULT_DURATION)) def format_description(resources): descriptions = [] # TODO: i18n ? for key, display in {'trainees': 'Filières', 'instructors': 'Intervenants', 'category5s': 'Matières'}.items(): if key in resources: descriptions.append( f'{display} : ' + ','.join([x['name'] for x in resources[key]])) return '\n'.join(descriptions) filename = filename or self.ics_calendar_filename calendar = Calendar() if self.events_nb > settings.ADE_MAX_EVENTS: logger.warning(f'Too much events for {self.username} : {self.events_nb}') e = Event() e.name = "Votre calendrier dépasse le nombre d'événements autorisé" e.begin = format_ics_date('01/01/2000 00:00') e.end = format_ics_date('01/01/2100 00:00') calendar.events.add(e) else: merged_events = self.events events = merged_events.get('events', []) # merged_events = {r: merged_events.get(r, {}) for r in res_list} if events: filename = filename or self.ics_calendar_filename res_list = ('trainees', 'instructors', 'classrooms', 'category5s') for event in events: # Keeps adding 5000 events under 1 sec resources = {} for r in res_list: res = [merged_events[r][e] for e in event.get(r, [])] if res: resources[r] = res classrooms = resources.get('classrooms', ()) begin_time = format_ics_date( f'{event["date"]} {event["startHour"]}') # Genereate ICS event e = Event() e.name = event['name'] e.begin = begin_time e.end = format_end_date(begin_time, event['duration']) e.geo = format_geolocation(classrooms) e.location = ';'.join(map(format_ics_location, classrooms)) # e.last_modified = event['lastUpdate'] e.description = format_description(resources) calendar.events.add(e) if self.events_nb > 0: with default_storage.open(filename, 'w') as fh: return fh.write(str(calendar))
event = Event( timespan=EventTimespan(begin_time=datetime.datetime(2021, 7, 19, 9, 0, tzinfo=tzinfo), end_time=datetime.datetime(2021, 7, 19, 10, 0, tzinfo=tzinfo), duration=None, precision='second'), summary='A. Person (MVA Physio Subsequent)', uid='*****@*****.**', description='', location= 'Some Physical Therapy Centres - 1234 St Unnamed Blvd, 123, Ottawa', url=None, status='CONFIRMED', created=None, last_modified=None, dtstamp=datetime.datetime(2021, 8, 18, 11, 32, 51, tzinfo=Timezone.from_tzid('UTC')), alarms=[], attach=[], classification=None, transparent=None, organizer=organizer, geo=None, attendees=[], categories=[])
'C': 'Conrad', 'D': 'Donovan', 'E': 'Emery', 'F': 'Frisk', 'G': 'Gonzalez' } student: Student = Student('hpeng2021', 'Michael Peng', schedules={2: student_schedule}) case = IcsCalendarCase() ahs_timezone = 'America/New_York' expected_events = { Event(name='A Block with Aubrey', begin=Arrow(2020, 4, 6, 8, 30, tzinfo=ahs_timezone), end=Arrow(2020, 4, 6, 9, 15, tzinfo=ahs_timezone), categories=['AHS at home', 'AHS at home: A Block'], alarms=[AudioAlarm(-datetime.timedelta(minutes=5))]), Event(name='C Block with Conrad', begin=Arrow(2020, 4, 6, 9, 30, tzinfo=ahs_timezone), end=Arrow(2020, 4, 6, 10, 15, tzinfo=ahs_timezone), categories=['AHS at home', 'AHS at home: C Block'], alarms=[AudioAlarm(-datetime.timedelta(minutes=5))]), Event(name='E Block with Emery', begin=Arrow(2020, 4, 6, 10, 30, tzinfo=ahs_timezone), end=Arrow(2020, 4, 6, 11, 15, tzinfo=ahs_timezone), categories=['AHS at home', 'AHS at home: E Block'], alarms=[AudioAlarm(-datetime.timedelta(minutes=5))]), Event(name='G Block with Gonzalez', begin=Arrow(2020, 4, 6, 11, 30, tzinfo=ahs_timezone), end=Arrow(2020, 4, 6, 12, 15, tzinfo=ahs_timezone),
def make_event(course): # Take a course object and turn it into an ics Event object e = Event() e.name = course.number + " " + course.name e.begin = make_time(course.starttime) e.end = make_time(course.endtime)
sys.exit(1) c = Calendar() with sys.stdin as csvfile: reader = csv.DictReader(csvfile) for field in reader.fieldnames: if not field in ['summary', 'location', 'dtstart', 'dtend']: warning("the field '%s' is ignored" % field) for field in ['summary', 'location', 'dtstart', 'dtend']: if not field in reader.fieldnames: fail("missing field '%s'" % field) for row in reader: dtstart = dateparser.parse(row['dtstart']) dtend = dateparser.parse(row['dtend']) e = Event( name=row['summary'], location=row['location'], begin=dtstart.isoformat(), end=dtend.isoformat(), ) c.events.add(e) with sys.stdout as f: f.writelines(c)
def main(): # Use a breakpoint in the code line below to debug your script. print("The program has been started!") # Press ⌘F8 to toggle the breakpoint. anniversary_date = date(2020, 4, 14) # This time is UTC + 0, Germany is UTC + 2 default_start_time = ' 00:00:00' c = Calendar() total_day_passed = 0 total_months_passed = 0 total_years_passed = 0 end_date = date(2150, 1, 1) # Looping through all dates between the anniversary and the specified end date for single_date in daterange(anniversary_date, end_date): current_date_string = single_date.strftime("%Y-%m-%d") print(current_date_string) # Current day matches anniversary day if single_date.day == anniversary_date.day: if single_date.month == anniversary_date.month: e = Event() e.name = "Zusammen seit " + str(total_years_passed) + " Jahren" e.begin = current_date_string + default_start_time e.make_all_day() c.events.add(e) total_years_passed += 1 else: e = Event() e.name = "Zusammen seit " + str(total_months_passed) + " Monaten" e.begin = current_date_string + default_start_time e.make_all_day() c.events.add(e) total_months_passed += 1 # Checking if multiple of 100 if total_day_passed % 100 == 0: e = Event() e.name = "Zusammen seit " + str(total_day_passed) + " Tagen" e.begin = current_date_string + default_start_time e.make_all_day() c.events.add(e) # Checking if days is a repdigit if len(list(set(str(total_day_passed)))) == 1 and total_day_passed > 10: e = Event() e.name = "Zusammen seit " + str(total_day_passed) + " Tagen" e.begin = current_date_string + default_start_time e.make_all_day() c.events.add(e) # Keeping track of how many days passed total_day_passed += 1 print(c.events) with open('anniversary.ics', 'w') as my_file: my_file.writelines(c)
start_time = datetime.now() #Read user and pass from file file = open('account.key', 'r') key = file.readlines() url = key[0].replace('url=', '') user = key[1].replace('user='******'') pwd = key[2].replace('pass='******'') tz = key[3].replace('timezone=', '') file.close() homework = all_homework(url, user, pwd) #Grabs all homework onto list cal = Calendar() for course, assignment in homework.items(): for homework, due in assignment.items(): time = parse(due).astimezone(gettz(tz)) print('{} {} {}'.format(homework, due, time)) cal.events.append( Event(name=homework, begin=time - timedelta(hours=1), end=time, description=course)) with open('WebAssign.ics', 'w') as f: f.writelines(cal) end_time = datetime.now() - start_time print(end_time)
def ical2notion(database, token, icals, verbose): """Google calendar to notion made simple.""" # Download the users ical files and get all events events = [] for url in icals: # Log if verbose if verbose == 1: click.echo(f"Downloading calendar from {url}") try: c = Calendar(requests.get(url).text) events += list(c.timeline) except Exception as e: # Echo the exception if verbose verbose if verbose == 2: click.echo("Exception occured while downloading calendar: {e}", err=True) # Echo that it failed if just verbose else: click.echo("Exception occured while downloading calendar", err=True) events = [e for e in events if e > Event(begin=datetime.now())] # Authenticate with notion try: client = NotionClient(token_v2=token) except requests.exceptions.HTTPError as e: # Echo the exception if verbose verbose if verbose == 2: click.echo( "Exception occured while authenticating with notion: {e}", err=True) # Echo that it failed if just verbose else: click.echo("Exception occured while authenticating with notion", err=True) # Add each event to the notion database try: gcal_table = client.get_collection_view(database) except Exception as e: # Echo the exception if verbose verbose if verbose == 2: click.echo( "Exception occured while accessing notion database: {e}", err=True) # Echo that it failed if just verbose else: click.echo("Exception occured while accessing notion database", err=True) for event in events: # Check that it isn't in there cont = True for row in gcal_table.collection.get_rows(): if row.Name == event.name: add_or_update(row, event) cont = False break if cont: row = gcal_table.collection.add_row() add_or_update(row, event)
Game(ground, reg.group(1), reg.group(2), reg.group(3), reg.group(4))) other_games = reg.group(5) # convert our list of matches into a iCalendar c = Calendar() for match in matches: name = "" if not args.team: name = "{} vs {}".format(match.home, match.away) elif args.team in match.home: name = "{} vs {}".format(match.home, match.away) elif args.team in match.away: name = "{} vs {}".format(match.away, match.home) else: continue e = Event(name=name, begin=match.date, location=match.ground) c.events.add(e) if not len(c.events) and args.team: print( "Did not find any matches for {}. Make sure it is spelt same as it is in the pdf" .format(args.team)) filename = args.filename.split(".")[0] + ".ics" if (args.output): filename = args.output + ".ics" with open(filename, "w") as my_file: my_file.writelines(c)
def __init__(self, school_year): """Creates the class :param school_year: Starting year for the school year :type school_year: int """ # Initialize school calendar school_calendar = {} # Get holidays from National Education Ministry with open("Calendrier_Scolaire_Zone_B.ics", "r") as cal: edu_calendar = icsCalendar(cal.read()) # Initialize days off ICS calendar days_off_school = icsCalendar() # Define begin/end of the school year we are in for event in edu_calendar.events: if ("Rentrée scolaire des élèves" in event.name and event.begin.year == school_year): school_begin = event.begin continue if "Vacances d'été" in event.name and event.begin.year == school_year + 1: school_end = event.begin days_off_school.events.add(event) continue # Add events between begin and end of school year # First add school holidays, starting the day after the beginning for event in edu_calendar.events: if event.begin > school_begin and event.begin < school_end: # Remove 1s to end so that it does not overrides next day event._end_time = event._end_time.shift(seconds=-1) days_off_school.events.add(event) # Then take holidays from workalendar calendar = France() for year in [school_year, school_year + 1]: for day_off in calendar.holidays(year): begin = day_off[0] event = Event(day_off[1], begin) event.make_all_day() if event.begin > school_begin and event.begin < school_end: # Remove 1s to end so that it does not overrides next day event.end = event.end.shift(seconds=-1) days_off_school.events.add(event) # Create timeline object timeline = days_off_school.timeline def get_last_tue(date): while date.weekday() != 1: date = date.shift(days=-1) return date def set_end(date): return date.replace(hour=16, minute=30, second=0, microsecond=0) # Now create dict of all days of school year and status # ordered by week number current = school_begin while int(current.strftime("%w")) > 1: current = current.shift(days=-1) while current < school_end: day = current.strftime("%d") week_number = current.isocalendar()[1] if week_number not in school_calendar.keys(): school_calendar[week_number] = [] current_week = school_calendar[week_number] # Limite cantine limit = set_end( get_last_tue( current.shift( weeks=-1) if current.weekday() >= 1 else current)) past_cantine = arrow.now() > limit past_garderie = current < arrow.now() month = current.strftime("%B").capitalize() data = { "day": day, "month": month, "date": current.strftime("%Y%m%d") } # If one of these is past, then save immediately data["bookable_cantine"] = not past_cantine data["bookable_garderie"] = not past_garderie if not data["bookable_cantine"] and not data["bookable_garderie"]: current_week.append(data) current = current.shift(days=+1) continue if current.isoweekday() in NON_WORKING_DAYS or current.isoweekday( ) in [ 6, 7, ]: data["bookable_cantine"] = False data["bookable_garderie"] = False data["bookable"] = False current_week.append(data) elif len([i for i in timeline.at(current)]) > 0: data["bookable_cantine"] = False data["bookable_garderie"] = False data["bookable"] = False current_week.append(data) elif current < school_begin: data["bookable_cantine"] = False data["bookable_garderie"] = False data["bookable"] = False current_week.append(data) else: data["bookable"] = True current_week.append(data) current = current.shift(days=+1) # Create set of periods i = 1 periods = { i: { "begin": school_begin.format("YYYYMMDD"), "begin_pretty": school_begin.format("DD/MM/YYYY"), } } for event in sorted(edu_calendar.events): if event.begin < school_begin: continue if event.begin > school_end: continue if "Vacances" in event.name: periods[i]["end"] = event.begin.format("YYYYMMDD") periods[i]["end_pretty"] = event.begin.format("DD/MM/YYYY") i += 1 periods[i] = { "begin": event.end.format("YYYYMMDD"), "begin_pretty": event.end.format("DD/MM/YYYY"), } periods.pop(i) self.periods = periods self.calendar = school_calendar
dateKey = "event-date" titleKey = "title" uuidKey = "nid" startDateKey = "value" endDateKey = "value2" dateNodeLevel = 0 for eventNasa in resutlHits: eventTitle = eventNasa[sourceNodeKey][titleKey] eventDateBegin = eventNasa[sourceNodeKey][dateKey][dateNodeLevel][ startDateKey] eventDateEnd = eventNasa[sourceNodeKey][dateKey][dateNodeLevel][ endDateKey] eventUuid = eventNasa[sourceNodeKey][uuidKey] """ Event creation """ event = Event() """ Event data """ event.name = eventTitle event.begin = eventDateBegin event.end = eventDateEnd event.uid = eventUuid #unique to event #Add event to calendar calendarObject.events.add(event) """ write calendar file """ wf.writeFile('space-calendar_spaceA.ics', calendarObject) except requests.RequestException as err: print(err)
def create5DayWeek(courseNames, y, m, d): #List of modified durations for long days on 5 day schedule dur5 = [15, 60, 15, 15, 60, 15, 45, 60, 15, 15, 105] #List of names for each event depending on the day of the week mNames = [ "Advisory/Community Flex Time", courseNames[0], courseNames[0] + " Flex", "Break", courseNames[2], courseNames[2] + " Flex", "Lunch", courseNames[4], courseNames[4] + " Flex", "Break", courseNames[6], courseNames[6] + " Flex", "Conferencing" ] tNames = [ "Advisory/Community Flex Time", courseNames[1], courseNames[1] + " Flex", "Break", courseNames[5], courseNames[5] + " Flex", "Lunch", courseNames[7], courseNames[7] + " Flex", "Break", "Conferencing" ] wNames = [ "Advisory/Community Flex Time", courseNames[3], courseNames[3] + " Flex", "Break", courseNames[4], courseNames[4] + " Flex", "Lunch", courseNames[6], courseNames[6] + " Flex", "Break", "Conferencing" ] thNames = [ "Advisory/Community Flex Time", courseNames[0], courseNames[0] + " Flex", "Break", courseNames[2], courseNames[2] + " Flex", "Lunch", courseNames[5], courseNames[5] + " Flex", "Break", "Faculty Collaboration" ] fNames = [ "Advisory/Community Flex Time", courseNames[1], courseNames[1] + " Flex", "Break", courseNames[3], courseNames[3] + " Flex", "Lunch", courseNames[7], courseNames[7] + " Flex", "Break", "Conferencing" ] #The outer loop makes this run for each day of the week for z in range(1, 6): #Chooses which set of names and durations to use based the day of the week if (z == 1): names = mNames duration = dur elif (z == 2): names = tNames duration = dur5 elif (z == 3): names = wNames duration = dur5 elif (z == 4): names = thNames duration = dur5 else: names = fNames duration = dur5 #The inner loop makes this run for each class in the day for x in range(len(names)): #if statement make it so events are only created for named courses if (names[x] != "" and names[x] != " Flex"): #creates datetime for a class beg = datetime.datetime(y, m, d, hrs[x], mins[x]) #Adjusts date using z. This is in a separate statement so that the #added day makes the month roll over if necessary beg += datetime.timedelta(days=z - 1) #Creates calendar event e = Event(name=names[x], begin=beg, duration={"minutes": duration[x]}) #Adds event to calendar c.events.add(e) c.events #Prints calendar file to console print(str(c)) #Saves calendar file to console #I just keep writing to the same calendar. Haven't had issues with this but it could possibly cause issues. open('my.ics', 'w').writelines(c)
print("./weeks.py startyear startmonth startdate numweeks breakweek") sys.exit(1) # Get user data if len(sys.argv) != 6: usage() start = date(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3])) num_weeks = int(sys.argv[4]) break_week = int(sys.argv[5]) c = Calendar() # Create calendar & events for i in range (0, num_weeks + 1): if i == break_week: e = Event() e.name = "Mid Semester Break" begin = start + timedelta(weeks=+(i)) e.begin = begin.strftime("%Y-%m-%d %X") end = begin + timedelta(days=+4) e.end = end.strftime("%Y-%m-%d %X") e.make_all_day() c.events.add(e) else: e = Event() if i > break_week: curr_week = i
import sys import datetime import time import json from ics import Calendar, Event filename = sys.argv[1] jfile = open(filename, "r") if jfile.mode == "r": jdata = jfile.read() jfile.close() data = json.loads(jdata) c = Calendar() for meeting in data: if meeting["Name"] != "": newEvent = Event() newEvent.name = meeting["Name"] newEvent.begin = meeting["Beginning"] newEvent.end = meeting["Ending"] newEvent.description = "Meets in room " + meeting["Room"] + "." c.events.append(newEvent) print(str(c))
calAll = Calendar() calBase = Calendar() calKom = Calendar() calAnw = Calendar() calEvs = Calendar() calVsi = Calendar() js = [] for event in data: #pprint(event) ev = Event() ev.name = event['description'] ev.begin = event['start'] ev.end = event['end'] ev.location = event['room'] des = event['instructor'] + ' ' + event['title'] ev.description = des calAll.events.add(ev) if ("3IT-PMA" in ev.description): color = "#cf2c08" calAnw.events.add(ev) elif("3IT-MK" in ev.description):
def main(): st.title("SLOE ML Web App") html_temp = """ <div style="background-color:tomato;padding:10px"> <h2 style="color:white;text-align:center;">Menstruation Cycle Predictor </h2> </div> """ name = st.text_input("Enter your Child's name: ") email = st.text_input("Enter your Email-id: ") day = st.text_input("Enter Day: ") month = st.text_input("Enter Month: ") year = st.text_input("Enter Year: ") if st.button("Know More"): html_temp = """ <div> <h3 style="color:red;text-align:left;">0 = Attentive </h3> <h3 style="color:red;text-align:left;">1 = Unattentive </h3> <h3 style="color:red;text-align:left;">2 = Confused </h3> <h3 style="color:red;text-align:left;">3 = Depressed</h3> <h3 style="color:red;text-align:left;">4 = Cheerful </h3> </div> """ st.markdown(html_temp, unsafe_allow_html=True) if st.button("Predict"): result = mood_recog(day, month, year, 0, 0, 1, 0, 4) if int(result) == 0: st.success("Your child was Attentive during the day.") if int(result) == 1: st.success("Your child was Unattentive during the day.") if int(result) == 2: st.success("Your child was Confused during the day.") if int(result) == 3: st.success("Your child was Depressed during the day.") if int(result) == 4: st.success("Your child was Happy during the day.") import ics as icsneo import calendar from ics import Calendar, Event final = str(year) + "-" + str(month) + "-" + str(day) + " 00:00:00" print(final) c = Calendar() e = Event() e.name = "Mood of your child today:" e.begin = final c.events.add(e) c.events with open('my.ics', 'w') as my_file: my_file.writelines(c) import smtplib from email.message import EmailMessage EMAIL_ADDRESS = "*****@*****.**" EMAIL_PASSWORD = "******" msg = EmailMessage() msg['Subject'] = 'Your child daily behaviour: ' msg['From'] = EMAIL_ADDRESS msg['To'] = email msg.set_content('Your child was Happy during the day.') files = ['my.ics'] for file in files: with open(file, 'rb') as f: file_data = f.read() file_name = f.name msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) smtp.send_message(msg) st.line_chart(data=Data, width=0, height=0, use_container_width=True) st.bar_chart(Data)
@pytest.mark.parametrize('text,expected', [ (None, None), ('', None), ('lorem ipsum dolor sit amet', None), ('https://python.cz', 'https://python.cz'), ('http://python.cz', 'http://python.cz'), ('lorem ipsum https://python.cz dolor sit amet', 'https://python.cz'), ('lorem https://python.cz ipsum https://pyvo.cz', 'https://python.cz'), ]) def test_find_first_url(text, expected): assert find_first_url(text) == expected @pytest.mark.parametrize('event,expected_url', [ (Event(), None), (Event(url='https://python.cz'), 'https://python.cz'), (Event(description='https://pyvo.cz', url='https://python.cz'), 'https://python.cz'), (Event(description='https://pyvo.cz'), 'https://pyvo.cz'), (Event(description=''' See: https://www.meetup.com/PyData-Prague/events/257775220 Looking forward to see you! '''), 'https://www.meetup.com/PyData-Prague/events/257775220'), ]) def test_set_url_from_description(event, expected_url): assert set_url_from_description(event).url == expected_url
#PARSE THROUGH .ics FILE AND SAVE EVENT INFORMATION $ pip install ics >>> from ics import Calendar, Event >>> c = Calendar() >>> e = Event() >>> e.name = "My cool event" >>> e.begin = '20140101 00:00:00' >>> c.events.append(e) >>> c.events [<Event 'My cool event' begin:2014-01-01 00:00:00 end:2014-01-01 00:00:01>] >>> with open('my.ics', 'w') as my_file: >>> my_file.writelines(c) >>> # and it's done !
def create_event(begin, end, is_exclude): return Event(status=("CANCELLED" if is_exclude else None), end=end, begin=begin, name="Рабочая смена", uid=begin.format("YYYY_MM_DD") + "_date")
def makeFile(week=5): c = Calendar() today = datetime.date.today() chetn = 0 # UserParams.getChetn() current_date = today - datetime.timedelta( days=today.isoweekday()) + datetime.timedelta(days=1) days_in_week = list(response.keys()) days_in_week.sort() current_week = 0 while (current_week <= week): for key in days_in_week: if (current_date.month == 12 and current_date.day == 30) or (current_date.month == 7 and current_date.day == 1): break for row in response[key]: dayDate = row["dayDate"].rstrip().lower() chetnost = True if ( datetime.date(current_date.year, current_date.month, current_date.day).isocalendar()[1] + chetn) % 2 else False # Если True чет, False - неч prefix = "" if (dayDate == 'чет' and not chetn) or (dayDate == 'неч' and chetn): continue elif dayDate == 'чет/неч': if chetnost: prefix = " (1) гр." else: prefix = " (2) гр." elif dayDate == 'неч/чет': if chetnost: prefix = " (2) гр." else: prefix = " (1) гр." e = Event() tt = row["dayTime"].rstrip() if len(row["dayTime"].rstrip( )) < 6 else row["dayTime"].rstrip()[:5] tt = tt_dict[tt] begin_time = str(current_date) + " {}:00".format(tt) # end_time = str(current_date) + " {}:00".format(time_dict[row["dayTime"].rstrip()]) e.name = prefix + row["disciplType"].rstrip().upper( ) + " " + row["disciplName"].rstrip() e.begin = begin_time e.duration = datetime.timedelta( minutes=190 if row["disciplType"].rstrip().upper() == 'Л.Р.' else 90) e.location = "В {} ауд. {} зд".format(row["audNum"].rstrip(), row["buildNum"].rstrip()) e.description = "В {} ауд. {} зд".format( row["audNum"].rstrip(), row["buildNum"].rstrip()) c.events.add(e) current_date = current_date + datetime.timedelta(days=1) if str(current_date.isoweekday()) not in days_in_week: current_date = current_date + datetime.timedelta(days=1) continue current_week += 1 with open('my.ics', 'w') as f: f.write(str(c))
def construct_and_write_calendar_files(cal_dict, bold: bool): now = datetime.now() date = now.strftime('%m-%d-%Y') calendar = Calendar() if bold: filename = date + ' bold calendar items' else: filename = date + ' all calendar items' # with open(f'{filename}.csv', 'w') as csvfile: # cal_writer = csv.writer(csvfile) # cal_writer.writerow(['Subject', # 'Start Date', 'Start Time', # 'End Date', 'End Time', # 'Description', 'Location']) for date, events in cal_dict.items(): # create the correct date format for all events within a day parts = date.split(',') year = parts[2][1:] month_day = parts[1].split(' ') month = month_dict[month_day[1]] day = month_day[2] date_combined = year + '/' + month + '/' + day for event in events: # subject subject = event[1] # start date and time start_date = date_combined start_time = event[0] ics_start = datetime.strptime(start_date + ' ' + start_time, '%Y/%m/%d %I:%M %p') dst_adjust_start = (ics_start + timedelta(hours=4)) if is_dst() else ( ics_start + timedelta(hours=5)) # end date and time end_date = date_combined if event[0][-2] == 'A' and event[0][:2] == '11': end_time = '12:00 PM' elif event[0][:2] == '12': end_time = '1:00 PM' else: split_time = start_time.split(':') hour = split_time[0] minute = split_time[1][:2] if event[0][-2] == 'A': indicator = 'AM' else: indicator = 'PM' end_time = str(int(hour) + 1) + ':' + minute + ' ' + indicator ics_end = datetime.strptime(end_date + ' ' + end_time, '%Y/%m/%d %I:%M %p') dst_adjust_end = (ics_end + timedelta(hours=4)) if is_dst() else ( ics_end + timedelta(hours=5)) # description if len(event) == 4: description = event[2].replace('\n', '') else: description = '' # location location = event[-1] # cal_writer.writerow([subject, # start_date, start_time, # end_date, end_time, # description, location]) event = Event() event.name = subject event.begin = dst_adjust_start event.end = dst_adjust_end event.description = description event.location = location calendar.events.add(event) # write the ics to a file with open(f'{filename}.ics', 'w') as icsfile: icsfile.writelines(calendar)
NUM_MONTHS = 12 TIME = 18 cal = Calendar() today = datetime.today() pacific = pytz.timezone('US/Pacific') def dayOfNthMonth(n, day): today = datetime.today() year = today.year month = (today.month + n) % 12 + 1 year += int((today.month + n) / 12) return datetime(year, month, day, TIME) for month in range(NUM_MONTHS): for day in (5, 20): the_date = dayOfNthMonth(month, day) if the_date.weekday() == 6: the_date -= timedelta(days=2) elif the_date.weekday() == 5: the_date -= timedelta(days=1) e = Event(name="Submit expense report") e.begin = pacific.localize(the_date).astimezone(timezone.utc) e.duration = timedelta(minutes=15) cal.events.add(e) open("expense_reports.ics", "w").writelines(cal)
def generate_event_calendar(events): """ Generate a .ics file of events from a list of dictionaries. Arguments: events -- A list of dicts containing all matches. (list) """ cal = Calendar() # Set Calendar Metadata cal.extra.append(ContentLine(name='X-WR-CALNAME', value='KQB Events')) cal.extra.append( ContentLine( name='X-WR-CALDESC', value= 'Upcoming matches and events in the Killer Queen Black community.') ) cal.extra.append(ContentLine(name='X-PUBLISHED-TTL', value='PT15M')) # Add all events to calendar for entry in events: event = Event() event.name = entry['name'] event.begin = dp.parse(entry['start_time']) if entry['duration']: date_obj = datetime.strptime(entry['duration'], '%H:%M:%S') delta = timedelta(hours=date_obj.hour, minutes=date_obj.minute, seconds=date_obj.second) event.duration = delta else: event.duration = timedelta(minutes=60) # Base Description description = str(entry['description']) # Event Links if entry['links']: description += '\n\n[Event Links]\n' for link in entry['links']: description += f"\n{link['name']}:\n{link['url']}\n" # Organizers if entry['organizers']: description += '\n\n[Organizers]\n' for organizer in entry['organizers']: description += f"{organizer['name']}" if organizer['discord_username']: description += f"discord: @{organizer['discord_username']}\n" if organizer['twitch_username']: description += f"twitch: https://twitch.tv/{organizer['twitch_username']}\n" description += '\n\n' # Finalize Description event.description = description # Finalize Event cal.events.add(event) with open('events.ics', 'w') as cal_file: cal_file.writelines(cal)
def debug_event(): eve = Event() eve.name = "Sahri Ends" # ev["title"] eve.begin = '2020-04-25T05:29:00+08:00' # ev["start_time"] c.events.add(eve)
def generate_match_calendar(matches): """ Generate a .ics file of matches from a list of dictionaries. Arguments: matches -- A list of dicts containing all matches. (list) """ cal = Calendar() # Set Calendar Metadata cal.extra.append(ContentLine(name='X-WR-CALNAME', value='KQB Matches')) cal.extra.append( ContentLine( name='X-WR-CALDESC', value= 'Upcoming matches and events in the Killer Queen Black community.') ) cal.extra.append(ContentLine(name='X-PUBLISHED-TTL', value='PT15M')) cal.extra.append(ContentLine(name='TZNAME', value='UTC')) # Add all events to calendar for match in matches: event = Event() home_team = match['home'] away_team = match['away'] if match['circuit']['name']: circuit_name = match['circuit']['name'] else: circuit_name = match['circuit']['verbose_name'] circuit_abbrev = f"{match['circuit']['tier']}{match['circuit']['region']}" # This should not happen anymore, but just to be safe. if (not home_team or not away_team): continue event.name = f"{circuit_abbrev} {away_team['name']} @ {home_team['name']}" event.begin = dp.parse(match['start_time']) event.duration = timedelta(minutes=60) # Tier and Circuit description = f'🌐 {circuit_name}' # Add Caster Details to Description if match['primary_caster']: description += f'\n\n🎙️ Casted by {match["primary_caster"]["name"]}' if match['secondary_casters']: description += f'\nCo-Casted by ' for cocaster in match['secondary_casters']: description += cocaster + ',' # Get rid of trailing comma description = description.rstrip(',') # Stream Link if match['primary_caster']['stream_link']: description += f"\n{match['primary_caster']['stream_link']}" # Away Team Stats description += f"\n\n🔷 {away_team['name']} [{away_team['wins']}W/{away_team['losses']}L]" description += '\n\n' for member in away_team['members']: description += f"{member['name']}, " description = description.rstrip(', ') # Home Team Stats description += f"\n\n🔶 {home_team['name']} [{home_team['wins']}W/{home_team['losses']}L]" description += '\n\n' for member in home_team['members']: description += f"{member['name']}, " description = description.rstrip(', ') event.description = description # Finalize Event cal.events.add(event) with open('matches.ics', 'w') as cal_file: cal_file.writelines(cal)
if __name__ == '__main__': df_cb_dates = scrape_cb_dates() str_dir_ics = '.\ics_files' os.makedirs(str_dir_ics, exist_ok=True) d_sets = dict( zip(df_cb_dates.loc[:, 'fx_code'].unique(), [[x] for x in df_cb_dates.loc[:, 'fx_code'].unique()])) d_sets['G10'] = [ 'EUR', 'GBP', 'USD', 'CAD', 'NOK', 'SEK', 'AUD', 'NZD', 'CHF', 'JPY' ] d_sets['Major_EM'] = ['KRW', 'BRL', 'ZAR', 'TRY'] # that page is missing MXN for some reason for idx_cur, cur_set in d_sets.items(): cal = Calendar() for idx, row in df_cb_dates[df_cb_dates['fx_code'].isin( cur_set)].iterrows(): e = Event() e.name = f"{row['fx_code']} CB Meeting" e.begin = f"{row['date'].strftime('%Y-%m-%d')}" e.make_all_day() cal.events.add(e) cal.events # write ics file with open(os.path.join(str_dir_ics, f"{idx_cur}_2020_CB_Dates.ics"), 'w') as f: f.write(str(cal)) print('All done.')
def calendar_for_events(events): cal_events = [ Event(name=e.name, begin=e.start, end=e.end, uid=e.id) for e in events ] return Calendar(events=cal_events)
def query_timetable(request): school_code = None course_code = None if request.method == 'POST': number_of_courses = request.POST.get('number_of_courses') print("below is the number of courses") print(number_of_courses) number_of_courses = int(number_of_courses) list_of_queries = [] list_of_date_from_query = [] list_of_course_codes = [] list_of_assessment_name = [] list_of_item_name = [] list_of_deadline_dates = [] list_of_deadline_times = [] for i in range(number_of_courses): school_code = request.POST.get(f'school_select_{i}') print(school_code) course_code = request.POST.get(f'course_select_{i}') print(course_code) assessment = Assessment.objects.filter(school_code=school_code, course_code=course_code) list_of_queries.append(assessment) for assess in assessment: list_of_course_codes.append(assess.course_code) list_of_assessment_name.append(assess.assessment_name) list_of_item_name.append(assess.item_name) list_of_deadline_dates.append(assess.deadline_date) list_of_deadline_times.append(assess.deadline_time) if assess.deadline_date in list_of_date_from_query: pass else: list_of_date_from_query.append(assess.deadline_date) c = Calendar() print(len(list_of_course_codes)) for item in range(len(list_of_course_codes)): print("this is the item loop") print(item) e = Event() e.name = f'{list_of_course_codes[item]} - {list_of_assessment_name[item]} {list_of_item_name[item]}' e.begin = f'{list_of_deadline_dates[item]} {list_of_deadline_times[item]}' c.events.add(e) c.events # [<Event 'My cool event' begin:2014-01-01 00:00:00 end:2014-01-01 00:00:01>] with open('my deadlines.ics', 'w') as my_file: my_file.writelines(c) print(list_of_date_from_query) list_of_date_from_query.sort() print(list_of_date_from_query) # By date list_of_queries_by_date = [] for i in range(len(list_of_date_from_query)): deadline_date = list_of_date_from_query[i] assessment_by_date = Assessment.objects.filter( deadline_date=deadline_date) list_of_queries_by_date.append(assessment_by_date) context = { 'school_code': school_code, 'course_code': course_code, 'list_of_queries': list_of_queries, 'list_of_queries_by_date': list_of_queries_by_date } return render(request, 'managing_deadlines/results.html', context)
from datetime import date, timedelta from ics import Calendar, Event sites = ["Bath", "Bristol", "Cardiff", "Exeter"] offset = 0 # start with Bath start_date = date(2022, 2, 7) weeks_to_schedule = 12 # format = "%Y-%m-%d 00:00:00" num_sites = len(sites) working_week = 4 # number of days between Monday and Friday calendar_week_len = 7 calendar = Calendar() for week in range(weeks_to_schedule): monday = start_date + timedelta(days=(week * 7)) friday = monday + timedelta(days=working_week) site = sites[(week + offset) % num_sites] turn = Event() turn.name = f"{site} doing RT ticket dispatching" turn.begin = monday.strftime("%Y-%m-%d 00:00:00") turn.end = friday.strftime("%Y-%m-%d 23:59:59") turn.make_all_day() turn.transparent = True calendar.events.add(turn) with open("rt-rota.ics", "w") as f: f.writelines(calendar)