'Win32com outlook filter by date stopped working
I have a script, that shows email's from some range of dates. It was working till 29 of april, and now, it doesn't filter correctly...
import win32com.client
import os
from datetime import datetime, timedelta
outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace('MAPI')
messages = mapi.Folders("[email protected]").Folders("Inbox").Items
today = datetime.today()
start_time = today.replace(month=4,day=20, hour=0, minute=0, second=0).strftime('%Y-%m-%d %H:%M %p')
end_time = today.replace(month=5,day=2,hour=20, minute=0, second=0).strftime('%Y-%m-%d %H:%M %p')
messages = messages.Restrict("[ReceivedTime] >= '" + start_time
+ "' And [ReceivedTime] <= '" + end_time + "'")
messages.Sort("[ReceivedTime]", Descending=True)
for message in list(messages)[:5]:
print(message.Subject, message.ReceivedTime, message.SenderEmailAddress)
I was using https://www.codeforests.com/2021/05/16/python-reading-email-from-outlook-2/ as a tutorial.
Any ideas why it's not working as intended? Script doesn't show any messages at all right now.
Solution 1:[1]
Make sure that dates are formatted properly. Although dates and times are typically stored with a Date format, the Find and Restrict methods require that the date and time be converted to a string representation. To make sure that the date is formatted as Microsoft Outlook expects, use the Format function. For example, a VBA macro which shows how to use the Format function:
sFilter = "[ReceivedTime] > '" & Format("5/02/22 3:30pm", "ddddd h:nn AMPM") & "'"
Also it makes sense to Sort the collection before applying filters.
Read more about the Find/FindNext or Restrict methods in the following articles:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eugene Astafiev |
