Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Parsing date time
#1
OS: Windows 10
Python 3.6

I'm working on piecing together some base code for me to search through a folder in Outlook to locate a specific message for a specific date. I'm fairly happy with my progress but I'm a bit frustrated with my date/time output.

What I'm getting...
Output:
Sent: (datetime.date(2020, 3, 5), datetime.time(8, 8, 16)) Received: ('2020-03-05', '08:08:16.765000')
When what I want to see is...
Output:
Sent: 2020-03-05 08:08:16 Received: 2020-03-05 08:08:16
This example message was sent from myself to myself so I ended up with the same date/time value.

Some help getting this to the format I'm looking for would be greatly appreciated!

here is my code...
import win32com.client
import win32com
import os
outlook = win32com.client.Dispatch("outlook.Application").GetNameSpace("MAPI")

inbox=outlook.GetDefaultFolder(6)

messages = inbox.items
for message in messages:
    receipt = message.ReceivedTime.date()
    if str(receipt) == "2020-03-05":
        subject = message.Subject
        if str(subject) == "Test Message":
            subject=message.Subject
            datesent=message.senton.date()
            timesent=message.senton.time()
            sent = (datesent, timesent)
            receipt = str(message.ReceivedTime.date()), str(message.ReceivedTime.time())
            sender = message.Sender
            print ("Received:", receipt)
            print ("Subject:", subject) 
            print ("Sender:", sender)
            print ("Sent:", sent)
            print ("Received:", receipt)
    message.Close(0)
Through a cloudy window,
Kip...

“Progress means getting nearer to the place you want to be. And if you have taken a wrong turn, then to go forward does not get you any nearer.
If you are on the wrong road, progress means doing an about-turn and walking back to the right road; and in that case the man who turns back soonest is the most progressive man.” ― C.S. Lewis
Reply
#2
Believe it or not, I own a book that is entirely dedicated to dates and time.
Here's a good take on what you can do with datetime: https://pymotw.com/3/datetime/
strftime is the way to go for formatting: https://docs.python.org/3/library/dateti...e-behavior
Reply
#3
@Larz60+

Yep I believe it... interesting phenomena... I've been laying down code in one form or another for the last ~40 years. In that time, I have purchased a sum total of three books on coding in all those languages. So, I take up Python the first of the year out of necessity and now i have six Python related books. Not because it's hard, just because I'm fascinated with it.

Good stuff!

Thanks for the link!
Through a cloudy window,
Kip...

“Progress means getting nearer to the place you want to be. And if you have taken a wrong turn, then to go forward does not get you any nearer.
If you are on the wrong road, progress means doing an about-turn and walking back to the right road; and in that case the man who turns back soonest is the most progressive man.” ― C.S. Lewis
Reply
#4
Quote: I've been laying down code in one form or another for the last ~40 years.
I started in 1968.
Reply
#5
import datetime
import win32com.client
import win32com
import os


def date_format(date_time):
    return date_time.strftime("%Y-%m-%d %H:%M:%S")


outlook = win32com.client.Dispatch("outlook.Application").GetNameSpace("MAPI")
inbox = outlook.GetDefaultFolder(6)


messages = inbox.items
for message in messages:
    if message.ReceivedTime.date() == datetime.date(2020, 3, 5):
        subject = message.Subject
        if subject == "Test Message":
            subject = message.Subject
            sent = datetime.datetime.combine(
                message.senton.date(),
                message.senton.time(),
            )
            receipt = datetime.datetime.combine(
                message.ReceivedTime.date(),
                message.ReceivedTime.time(),
            )
            sender = message.Sender
            print("Received:", receipt)
            print("Subject:", subject) 
            print("Sender:", sender)
            print("Sent:", date_format(sent))
            print("Received:", date_format(receipt))
    message.Close(0)
subject should be already a str. I remove the str conversion.
Then you want to get messages from one given date. You can use datetime.date:
message.ReceivedTime.date() == datetime.date(2020, 3, 5)

Then you want to combine date and time for sent and receipt. This will return a new datetime object.

Printing the datetime as str is nearly the format you want to have. The microseconds are also there.
But you can make your own datetime str representation. I've done this in the function date_format.
Before you print, you convert the object with this function.

Code is not tested, so maybe there is somewhere a hidden typo.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
Larz60+,
I have it working with the suggestion to look at strftime(). Worked like a champ once I figured out the nuances to it.

DeaD_EyE,
I incorporated your suggestion in my if statement. While my statement was functional, your's is more elegant and required only one line.

Resulting code is below, which I have several other things to add to it, but got me to the beginning point I wanted to start with. Much appreciation guys!

import win32com.client
import win32com
import os
import datetime

outlook = win32com.client.Dispatch("outlook.Application").GetNameSpace("MAPI")
inbox=outlook.GetDefaultFolder(6)
messages = inbox.items

for message in messages:
    if message.ReceivedTime.date() == datetime.date(2020, 3, 5):
        subject = message.Subject
        if subject == "Test Message":
            print(" ")
            subject=message.Subject
            print ("Subject:", subject) 
            sender = message.Sender
            print ("    Sender  :", sender)
            print(" ")
            timesent = message.senton.strftime("%m/%d/%Y %H:%M:%S")
            print("    Sent    :", timesent)
            receipttime = message.ReceivedTime.strftime("%m/%d/%Y %H:%M:%S")
            print("    Received:",  receipttime)
    message.Close(0)
Output:
Subject: Test Message Sender : Carter, Kenneth (138-Extern-Matrix) Sent : 03/05/2020 08:08:16 Received: 03/05/2020 08:08:16
Through a cloudy window,
Kip...

“Progress means getting nearer to the place you want to be. And if you have taken a wrong turn, then to go forward does not get you any nearer.
If you are on the wrong road, progress means doing an about-turn and walking back to the right road; and in that case the man who turns back soonest is the most progressive man.” ― C.S. Lewis
Reply
#7
Oh I see, the message.ReceivedTime is already a datetime object.
So the combine is not needed.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#8
I could start a new thread but what I thought was a no brainer add on to the code above has proven to be problematic. The initial code found the desired record by subject and date, once found I thought all I would have to do is the following to write any attachments to a folder of my choosing.

I'm not sure where I've gone off the rails here!

 while True:
                attachment = message.Attachments
                attachment_items = attachment.Count
                x = 1
                while x <= attachment_items:
                    attachment = attachment.item(x)
                    attachment.SaveAsFile('C:\\BarTender' + '\\'+ str(attachment)) 
                break    
Error:
File "c:\Users\cartken\Downloads\py\inbox scanner.py", line 36, in <module> attachment = attachment.item(x) File "C:\Python\lib\site-packages\win32com\client\dynamic.py", line 527, in __getattr__ raise AttributeError("%s.%s" % (self._username_, attr)) AttributeError: <unknown>.item
Been one of those 'daze'.
Through a cloudy window,
Kip...

“Progress means getting nearer to the place you want to be. And if you have taken a wrong turn, then to go forward does not get you any nearer.
If you are on the wrong road, progress means doing an about-turn and walking back to the right road; and in that case the man who turns back soonest is the most progressive man.” ― C.S. Lewis
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare current date on calendar with date format file name Fioravanti 1 226 Mar-26-2024, 08:23 AM
Last Post: Pedroski55
  Date Time Series Help...Please spra8560 2 362 Feb-01-2024, 01:38 PM
Last Post: spra8560
  Python date format changes to date & time 1418 4 603 Jan-20-2024, 04:45 AM
Last Post: 1418
  Downloading time zone aware files, getting wrong files(by date))s tester_V 9 1,031 Jul-23-2023, 08:32 AM
Last Post: deanhystad
  Formatting a date time string read from a csv file DosAtPython 5 1,281 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  Wait til a date and time KatManDEW 2 1,427 Mar-11-2022, 08:05 PM
Last Post: KatManDEW
  Date format and past date check function Turtle 5 4,250 Oct-22-2021, 09:45 PM
Last Post: deanhystad
  How to add previous date infront of every unique customer id's invoice date ur_enegmatic 1 2,234 Feb-06-2021, 10:48 PM
Last Post: eddywinch82
  Naming the file as time and date. BettyTurnips 3 2,978 Jan-15-2021, 07:52 AM
Last Post: BettyTurnips
  Update Date based on Time/String stevezemlicka 1 2,031 Jan-08-2021, 06:54 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020