将 Python 日期时间转换为 rfc 2822

发布于 2024-09-13 22:43:43 字数 475 浏览 7 评论 0原文

我想将 Python 日期时间转换为 RFC 2822 日期时间。我尝试过这些方法均无效:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

等你爱我 2024-09-20 22:43:43

下面是一些工作代码,为了清楚起见,将其分解为简单的部分:

>>> 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'

说明:email.utils.formatdate 需要一个时间戳——即自纪元以来包含秒数(及其小数部分)的浮点数。 datetime 实例不会直接为您提供时间戳 - 但是,它可以使用 timetuple 方法为您提供时间元组,并且time.mktime 当然可以从这样的元组中创建时间戳。

编辑:在 Python 3.3 及更高版本中,您可以通过更少的步骤执行相同的操作:

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

请参阅 format_datetime docs 了解有关使用的详细信息。

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.

狠疯拽 2024-09-20 22:43:43

如果您确实想要当前时间,只需调用不带参数的 formatdate 即可:

>>> from email.utils import formatdate
>>> formatdate()
'Tue, 10 Aug 2010 20:40:23 -0000'

但是,如果您必须向其传递参数,则需要 time.time 的输出(一个数字自 01/01/1970 以来的秒数):

>>> import time
>>> formatdate(time.time())
'Tue, 10 Aug 2010 20:41:43 -0000'

FWIW,datetime.datetime.now() 返回一个 datetime 对象,这不是 formatdate期望。

编辑添加:如果您已经有一个 datetime 对象,则可以将其格式化为 formatdate:

>>> import datetime
>>> dt = datetime.datetime.now()
>>> formatdate(float(dt.strftime('%s')))
'Tue, 10 Aug 2010 20:46:16 -0000'

编辑:Alex Martelli 指出 strftime 的“%s”格式字符串可能无法跨平台移植。正如他本人所建议的,一个可能的替代方案是:

>>> formatdate(time.mktime(dt.timetuple()))
'Tue, 10 Aug 2010 20:46:16 -0000'

If you indeed want the current time, just call formatdate with no arguments:

>>> from email.utils import formatdate
>>> formatdate()
'Tue, 10 Aug 2010 20:40:23 -0000'

But, if you must pass it an argument, you want the output of time.time (a number of seconds since 01/01/1970):

>>> import time
>>> formatdate(time.time())
'Tue, 10 Aug 2010 20:41:43 -0000'

FWIW, datetime.datetime.now() returns a datetime object, which is not what formatdate expects.

Edited to add: if you already have a datetime object, you can format it appropriately for formatdate:

>>> import datetime
>>> dt = datetime.datetime.now()
>>> formatdate(float(dt.strftime('%s')))
'Tue, 10 Aug 2010 20:46:16 -0000'

Edited: Alex Martelli noted that the '%s' format string for strftime may not be portable across platforms. A possible alternative would be, as he himself suggested,

>>> formatdate(time.mktime(dt.timetuple()))
'Tue, 10 Aug 2010 20:46:16 -0000'
悲凉≈ 2024-09-20 22:43:43

Python 3.3除了其他评论者提到的方法之外,还添加了一个format_datetime方法,该方法更加简洁:

>>> import datetime
>>> import email.utils
>>> dt = datetime.datetime.now()
>>> email.utils.format_datetime(dt)
'Thu, 09 Mar 2017 10:50:00 -0000'

Python 3.3, in addition to the methods mentioned by other commenters, also added a format_datetime method, which is much cleaner:

>>> import datetime
>>> import email.utils
>>> dt = datetime.datetime.now()
>>> email.utils.format_datetime(dt)
'Thu, 09 Mar 2017 10:50:00 -0000'
百变从容 2024-09-20 22:43:43

使用 strftime 的简单方法。 Python 2.7。注意:时区 = 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'

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'
沫尐诺 2024-09-20 22:43:43

如果您将此用于 HTTP 标头,并且需要 GMT 而不是 -0000

  • datetime,请使用 <代码>format_datetime(强调我的):

    <块引用>

    如果它是偏移量为零的感知时区,则 usegmt 可能会设置为
    True,在这种情况下,使用字符串 GMT 而不是数字
    时区偏移。


    <前><代码>>>>从日期时间导入日期时间、时区
    >>>>>从 email.utils 导入 format_datetime
    >>>>> format_datetime(datetime.now(timezone.utc), usegmt=True)
    '2021 年 10 月 27 日星期三 11:00:46 GMT'

  • 从时间戳中,使用formatdate

    <块引用>

    可选usegmt是一个标志,当True时,输出日期字符串
    时区为 ascii 字符串 GMT,而不是数字
    -0000...仅当本地时间False时才适用。


    <前><代码>>>>从 email.utils 导入格式日期
    >>>>>从导入时间开始
    >>>>>格式日期(时间(),usegmt=True)
    '2021 年 10 月 27 日星期三 11:05:29 GMT'

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'
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文