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
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.
The strftime() method returns a string representing date and time using date, time or datetime object.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With