views:

222

answers:

2

I am trying to retrieve date from an email. At first it's easy:

message = email.parser.Parser().parse(file)
date = message['Date']
print date

and I receive:

'Mon, 16 Nov 2009 13:32:02 +0100'

But I need a nice datetime object, so I use:

datetime.strptime('Mon, 16 Nov 2009 13:32:02 +0100', '%a, %d %b %Y %H:%M:%S %Z')

which raise ValueError, since %Z isn't format for +0100. But I can't find proper format for timezone in the documentation, there is only this %Z for zone. Can someone help me on that?

A: 

Have you tried

rfc822.parsedate_tz(date) # ?

More on RFC822, http://docs.python.org/library/rfc822.html

It's deprecated, though.

But maybe these answers help:

The MYYN
Yeah, I've seen it, but it's deprecated.
gruszczy
Is there any sense using it?
gruszczy
+3  A: 

email.utils has a parsedate() function for the RFC 2822 format, which AFAIK is not deprecated.

>>> import email.utils
>>> import time
>>> import datetime
>>> email.utils.parsedate('Mon, 16 Nov 2009 13:32:02 +0100')
(2009, 11, 16, 13, 32, 2, 0, 1, -1)
>>> time.mktime((2009, 11, 16, 13, 32, 2, 0, 1, -1))
1258378322.0
>>> datetime.datetime.fromtimestamp(1258378322.0)
datetime.datetime(2009, 11, 16, 13, 32, 2)
Ben James
Yep, those functions seems to have been moved to utils and email is fine to use. Thanks.
gruszczy