Skip to content

Instantly share code, notes, and snippets.

@jackqt
Created April 30, 2015 10:34
Show Gist options
  • Save jackqt/7b82b4def1c1c5a5ed67 to your computer and use it in GitHub Desktop.
Save jackqt/7b82b4def1c1c5a5ed67 to your computer and use it in GitHub Desktop.
Fetch calendar information of outlook from win32com API
from win32com.client import Dispatch
from tabulate import tabulate
import datetime
import pdb
OUTLOOK_FORMAT = '%m/%d/%Y %H:%M'
outlook = Dispatch("Outlook.Application")
ns = outlook.GetNamespace("MAPI")
appointments = ns.GetDefaultFolder(9).Items
# Restrict to items in the next 30 days (using Python 3.3 - might be slightly different for 2.7)
begin = datetime.date.today()
end = begin + datetime.timedelta(days = 30);
restriction = "[Start] >= '" + begin.strftime("%m/%d/%Y") + "' AND [End] <= '" +end.strftime("%m/%d/%Y") + "'"
restrictedItems = appointments.Restrict(restriction)
appointments.Sort("[Duration]")
appointments.IncludeRecurrences = "True"
# Iterate through restricted AppointmentItems and print them
calcTableHeader = ['Title', 'Organizer', 'Start', 'Duration(Minutes)'];
calcTableBody = [];
#pdb.set_trace()
for appointmentItem in appointments:
row = []
row.append(appointmentItem.Subject)
row.append(appointmentItem.Organizer)
row.append(appointmentItem.Start.Format(OUTLOOK_FORMAT))
row.append(appointmentItem.Duration)
calcTableBody.append(row)
print tabulate(calcTableBody, headers=calcTableHeader);
@Arun-R-Achuthan
Copy link

Hey, How to get events from shared calendar?

@shahidBashusha
Copy link

Hello, Thanks for posting this code
it's really helpful code for my project

@zb-saml
Copy link

zb-saml commented Nov 9, 2023

Wow! This is so helpful! Thanks!!

@aaronkirkman
Copy link

aaronkirkman commented Jan 22, 2024

Thank you for this code!
To only display items within the next 30 days, I replaced

appointments.Sort("[Duration]")
appointments.IncludeRecurrences = "True"

with

restrictedItems.Sort("[Duration]")
restrictedItems.IncludeRecurrences = "True"

and then iterated over restrictedItems instead of appointments in line 26.

@Waser2004
Copy link

Waser2004 commented Mar 5, 2024

Hey, How to get events from shared calendar?

You can use this code to see all the Calendars that you have in your Outlook:

for i, folder in enumerate(ns.GetDefaultFolder(9).Folders):
   print(f"{i + 1}, {folder.name}")

and then use the code below where you put in the right index and then can retrieve the appointments form the specific folder:

appointments = ns.GetDefaultFolder(9).Folders[<< index comes here >>].Items

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment