Convert Python datetime to rfc 2822

Adam Nelson picture Adam Nelson · Aug 10, 2010 · Viewed 20.2k times · Source

I want to convert a Python datetime to an RFC 2822 datetime. I've tried these methods to no avail:

>>> from email.Utils import formatdate
>>> import datetime
>>> formatdate(datetime.datetime.now())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/email    /utils.py", line 159, in formatdate
    now = time.gmtime(timeval)
TypeError: a float is required

Answer

Alex Martelli picture Alex Martelli · Aug 10, 2010

Here's some working code, broken down into simple pieces just for clarity:

>>> import datetime
>>> import time
>>> from email import utils
>>> nowdt = datetime.datetime.now()
>>> nowtuple = nowdt.timetuple()
>>> nowtimestamp = time.mktime(nowtuple)
>>> utils.formatdate(nowtimestamp)
'Tue, 10 Aug 2010 20:43:53 -0000'

Explanation: email.utils.formatdate wants a timestamp -- i.e., a float with seconds (and fraction thereof) since the epoch. A datetime instance doesn't give you a timestamp directly -- but, it can give you a time-tuple with the timetuple method, and time.mktime of course can then make a timestamp from such a tuple.

EDIT: In Python 3.3 and newer you can do the same in less steps:

>>> import datetime
>>> from email import utils
>>> nowdt = datetime.datetime.now()
>>> utils.format_datetime(nowdt)
'Tue, 10 Feb 2020 10:06:53 -0000'

See format_datetime docs for details on usage.