0

I'm getting the calendar results from outlook, fetching only the Start time and the Subject of each calendar item.

import win32com, win32com.client
import datetime, time, pytz

def getCalendarEntries():
    Outlook      = win32com.client.Dispatch("Outlook.Application")
    appointments = Outlook.GetNamespace("MAPI").GetDefaultFolder(9).Items
    appointments.Sort("[Start]");
    appointments.IncludeRecurrences = "True"
    today    = datetime.datetime.today().date().strftime("%Y-%d-%m")
    tomorrow = (datetime.date.today() + datetime.timedelta(days=1)).strftime("%Y-%d-%m")
    appointments = appointments.Restrict("[Start] >= '" +today+"' AND [Start] < '"+tomorrow+"'");
    events={'Start':[],'Subject':[]}
    for a in appointments: 
        events['Start'  ].append(a.Start  );
        events['Subject'].append(a.Subject)
    return events

calendar = getCalendarEntries();

n=len(calendar['Start']);
i=0;

while( n ):
    print(
        calendar['Start'][i]  , 
        calendar['Subject'][i]
    );
    n-=1;
    i+=1; 

This is the result, and it is correct:

$ py test_outlook.py
2019-12-06 10:00:00+00:00 test apointment 

What I need now is to manipule this data above to get only the time: 10:00, so that I can do calculations and find out how much time there is until the event starts... like if it's 10min away, 1h away, etc.

I really have no idea on how to do it... anyone has any idea?

Pedro Accorsi
  • 765
  • 1
  • 8
  • 21

2 Answers2

1

I am not sure what type getCalendarEntries returns. You can find out by adding an additional temporary line in your program:

print(type(calendar['Start'][i]))

If it is a datetime object, you can simply query the hour attribute:

hours = calendar['Start'][i].hour

If getCalendarEntries returns a POSIX timestamp, you can first convert it to a Python datetime object and then query the hour

dt = datetime.fromtimestamp(calendar['Start'][i])
hours = dt.hour

If it is a string, you can parse it using datetime.fromisoformat:

dt = datetime.datetime.fromisoformat(calendar['Start'][i])
hours = dt.hour
Omni
  • 1,002
  • 6
  • 12
1

Uri Goren seems to have answered the question here: https://stackoverflow.com/a/38992623/8678978

You need to use strptime with the datetime format to get a date object, and then you can extract the time portion.

dateString = '2019-12-06 10:00:00+00:00'
dateObject = datetime.datetime.strptime(str[0:19], '%Y-%m-%d %H:%M:%S')

Now you have a date object and can get the time parts using:

dateObject.hour
dateObject.minute
dateObject.second
chrisbyte
  • 1,408
  • 3
  • 11
  • 18