How do I convert RFC822 to a python datetime object?

怎甘沉沦 提交于 2019-11-28 22:47:26

问题


I know how to do this the other way around... it would be:

>>> dt.rfc822()
'Sun, 09 Mar 1997 13:45:00 -0500'

回答1:



In [1]: import rfc822     # This only works for python 2 series

In [2]: rfc822.parsedate_tz('Sun, 09 Mar 1997 13:45:00 -0500')
Out[2]: (1997, 3, 9, 13, 45, 0, 0, 1, 0, -18000)

in python3 parsedate_tz has moved to email.utils


>>> import email.utils   # this works on Python2.5 and up
>>> email.utils.parsedate_tz('Sun, 09 Mar 1997 13:45:00 -0500')
(1997, 3, 9, 13, 45, 0, 0, 1, -1, -18000)



回答2:


As of python 3.3 there is email.utils.parsedate_to_datetime(date)

>>> from email.utils import parsedate_to_datetime
>>> datestr = 'Sun, 09 Mar 1997 13:45:00 -0500'
>>> parsedate_to_datetime(datestr)
datetime.datetime(1997, 3, 9, 13, 45, tzinfo=datetime.timezone(datetime.timedelta(-1, 68400)))



回答3:


If you strip off the time zone, you can do it like this:

datetime.datetime.strptime('Sun, 09 Mar 1997 13:45:00', '%a, %d %b %Y %H:%M:%S')


来源:https://stackoverflow.com/questions/1568856/how-do-i-convert-rfc822-to-a-python-datetime-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!