Convert Python datetime to rfc 2822

Viewed 21150

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
5 Answers

Simple method using strftime. Python 2.7. Note: timezone = EST

>>> from datetime import datetime
>>> my_date = datetime.now()
>>> my_date.strftime('%a, %d %b %Y %H:%M:%S -0500')
'Wed, 22 Apr 2020 10:52:11 -0500'

If you're using this for e.g. a HTTP header, and want GMT rather than -0000:

  • From a datetime, use format_datetime (emphasis mine):

    If it is an aware timezone with offset zero, then usegmt may be set to True, in which case the string GMT is used instead of the numeric timezone offset.

    >>> from datetime import datetime, timezone
    >>> from email.utils import format_datetime
    >>> format_datetime(datetime.now(timezone.utc), usegmt=True)
    'Wed, 27 Oct 2021 11:00:46 GMT'
    
  • From a timestamp, use formatdate:

    Optional usegmt is a flag that when True, outputs a date string with the timezone as an ascii string GMT, rather than a numeric -0000... This only applies when localtime is False.

    >>> from email.utils import formatdate
    >>> from time import time
    >>> formatdate(time(), usegmt=True)
    'Wed, 27 Oct 2021 11:05:29 GMT'
    
Related