Email datetime parsing with python

I am trying to parse an email date using a python script.

In the mailbox, the value is similar below when I open the mail ...

from:    abcd@xyz.com
to:      def@xyz.com
date:    Tue, Aug 28, 2012 at 1:19 PM
subject: Subject of that mail

I use code like

mail = email.message_from_string(str1)
#to = re.sub('</br>','',mail["To"])
to = parseaddr(mail.get('To'))[1]
sender = parseaddr(mail.get('From'))[1]
cc_is = parseaddr(mail.get('Cc'))[1]
date = mail["Date"]
print date

Where as the output of the same datetime email using python parsing as shown below with a time offset.

Tue, 28 Aug 2012 02:49:13 -0500

Where I really hope for

Tue, Aug 28, 2012 at 1:19 PM

I am so confused between the relationship of these two meanings. Can someone help me figure this out, I need to get the same time in the mail details.

+5
source share
2 answers

GMail , . "Tue, 28 Aug 2012 02:49:13 -0500" , GMail.

stdlib

email.utils parsedate_tz() , .

, time.struct_time, . mktime_tz() ( UNIX). datetime.datetime().

formatdate(), UNIX , :

>>> from email.utils import parsedate_tz, mktime_tz, formatdate
>>> import time
>>> date = 'Tue, 28 Aug 2012 02:49:13 -0500'
>>> tt = parsedate_tz(date)
>>> timestamp = mktime_tz(tt)
>>> print formatdate(timestamp)
Tue, 28 Aug 2012 07:49:13 -0000

UTC, . ( ), localtime True:

>>> print formatdate(timestamp, True)
Tue, 28 Aug 2012 08:49:13 +0100

, , , formatdate() - (, GMail), .

python-dateutil ; , , .

>>> import dateutil.parser
>>> dt = dateutil.parser.parse(date)
>>> dt
datetime.datetime(2012, 8, 28, 2, 49, 13, tzinfo=tzoffset(None, -18000))

parse() datetime.datetime() , . .strftime(), , :

>>> print dt.strftime('%a, %b %d, %Y at %I:%M %p')
Tue, Aug 28, 2012 at 02:49 AM

, ; , .astimezone() tzone. python-dateutil .

( ):

>>> import dateutil.tz
>>> print dt.astimezone(dateutil.tz.tzlocal()).strftime('%a, %b %d, %Y at %I:%M %p')
Tue, Aug 28, 2012 at 09:49 AM

:

>>> print dt.astimezone(dateutil.tz.tzstr('Asia/Kolkata')).strftime('%a, %b %d, %Y at %I:%M %p')
Tue, Aug 28, 2012 at 07:49 AM
+20

, stdlib:

>>> from email.utils import parsedate_tz, mktime_tz, formatdate
>>> ts = mktime_tz(parsedate_tz('Tue, 28 Aug 2012 02:49:13 -0500'))
>>> formatdate(ts, localtime=True) # assuming Asia/Kolkata is the local timezone
'Tue, 28 Aug 2012 13:19:13 +0530'

PM :

>>> from datetime import datetime
>>> datetime.fromtimestamp(ts).strftime('%a, %b %d, %Y at %I:%M %p')
'Tue, Aug 28, 2012 at 01:19 PM'
+5

All Articles