How to get print data in text file ordered by date
<p>I have following code,</p>

<pre><code>import glob,os,win32com.client,datetime,time,email.utils,ctypes,sys
import Tkinter as tk
import tkFileDialog as filedialog
sys.path.append('C:\Windows\winsxs\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.1_none_e163563597edeada')

root = tk.Tk()
root.withdraw()
file_path = filedialog.askdirectory()
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders('Paper &amp; CD')
messages = inbox.Items
date_now = datetime.datetime.now()
#print date_now
date_before = (datetime.datetime.now() + datetime.timedelta(-30)).date()
#print date_before
#ctypes.windll.user32.MessageBoxA(0,'Current date is: '+str(date_now)+',It will fetch details from :'+str(date_before),"Information",0)
for msg in messages:
        for att in msg.Attachments:        
                if att.FileName == 'list.csv': 
                    att.SaveAsFile(file_path + "\\" + msg.subject + att.FileName)
                att.SaveAsFile(file_path + "\\" + att.FileName)
ctypes.windll.user32.MessageBoxA(0,'Download is finished,Now select files to count',"Information",0)
root = tk.Tk()
root.withdraw()
file_path = filedialog.askdirectory()
os.chdir(file_path)
date_now = datetime.datetime.now().date()
date_before = (datetime.datetime.now() + datetime.timedelta(-30)).date()
of = open("Info.txt", 'w')
for file in glob.glob("*.csv"):                
                of.write("\n\nFile Name:")
                of.write(file+"\n")
                fi = open(file)
                numline = len(fi.readlines())
                of.write("\n"+"Number of records:")
                of.write(str(numline-1)+"\n")
                of.write(str("\nCreated time:"))
                of.write(str(time.ctime(os.path.getctime(file)))+"\n")
                of.write(str("\nModified time:"))
                of.write(str(time.ctime(os.path.getmtime(file)))+"\n")  
of.close()
</code></pre>

<p>Now, It take attachements from outlook and stored into local path.
And then It create text document and write attachement detail into text file.</p>

<p>My output text file is like below.</p>

<pre><code>File Name:CD file for xxxlist.csv

Number of records:4

Created time:Sun Sep 04 17:25:32 2016

Modified time:Sun Sep 04 17:25:32 2016


File Name:CD file for xxlist.csv

Number of records:2

Created time:Mon Sep 12 10:23:08 2016

Modified time:Mon Sep 12 10:23:08 2016


File Name:CD file for xxlist.csv

Number of records:8

Created time:Thu Sep 15 17:32:23 2016

Modified time:Thu Sep 15 17:32:23 2016
</code></pre>

<p>I want 2 changes in code.
1)Time here displays the received time of mail.I want to change that into sent time.I want time format like below,</p>

<pre><code>"9/6/2016  10:15:00 AM"
</code></pre>

<p>2) My output file is listed based on the file name(Ascending order).
I want it to be based on time in which mail sent.
for example: If I received two mails(1st on sep 14 and 2nd mail on sep 15). I want details of the attachments which is on sep 15 mail and then other one.</p>

<p>I am newbie to Python,Help is appreciated.</p>

<p>You can use the <code>email</code> module to get the time you received the email. </p>

<pre><code>import email
# use email.message_from_string or email_message_from_file to make a email object
email_obj = email.message_from_file(my_file)  # my_file is a file object 
print email_obj.keys()  # shows you all available properties of the email
print email_obj.get('Date') # print the time of the email
</code></pre>

<p>As noted in the comments, please inspect the output from <code>email_obj.keys()</code>, if you need to extract any other information from the email</p>

<p>Edit: (expanded to handle time from email as datetime)</p>

<p>You can use <code>parsedate_tz</code> function from email module to get a tuple representing the datetime components. You can then use <code>datetime.strftime</code> to print as you desire</p>

<pre><code>from email import parsedate_tz
from datetime import datetime
dt_tuple = parsedate_tz(email_obj.get('Date'))

# [:7] on the tuple to ignore the timezone info. 
# If you need to process the timezone you need additional logic for that
datetime_obj = datetime(*dt_tuple[:7]) 
print datetime.strftime(datetime_obj, '%a %b %d %H:%M:%S %Y')
</code></pre>

python email