Python one-liner to convert IMAP timestring to UNIX timestamp

Monday, October 07, 2013

Recently I’ve played around with the imaplib module in Python. At first it’s hard to understand, if you never dealed with the IMAP-standard, because imaplib is kind of low-level.

If you want to get a UNIX timestamp from a mail’s date, the best solution in my opinion is the following, assuming you fetched a mail like this:

1
2
3
4
5
6
7
8
9
import imaplib
import email
import time
 
M = imaplib.IMAP4_SSL("imap.host.com")
M.login("my_user", "my_password")
M.select()
typ, data = M.fetch(mail_id, '(RFC822)')
my_mail = email.message_from_string(data[0][1])

Please note, that the RFC822-mail string gets parsed using the email module from the Python standard library.

The promised one-liner to parse the date looks like this:

1
time.mktime(email.utils.parsedate(my_mail['Date']))

email.utils.parsedate attempts to parse a date according to the rules in RFC 2822, which is crtitical, because not all mail-provider follow that standard (more info). It returns a 9-tuple.

In the next step time.mktime converts the 9-tuple to the UNIX timestamp. It is important to know, that the timestamp will be in local time, not UTC (more info).