Search code examples
pythondatetimeoutlookwin32com

Convert timestamp to time only


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

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

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?


Solution

  • 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