Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Python datetime to rfc 2822

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 
like image 335
Adam Nelson Avatar asked Aug 10 '10 20:08

Adam Nelson


People also ask

How do I convert datetime to different formats in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

How do I convert a datetime to a string in Python?

The strftime() method returns a string representing date and time using date, time or datetime object.

Is Python datetime in UTC?

You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object.


1 Answers

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.

like image 145
Alex Martelli Avatar answered Oct 01 '22 17:10

Alex Martelli