是否有一种相当简单的方法将datetime对象转换为RFC 1123(HTTP/1.1)日期/时间字符串,即具有以下格式的字符串

Sun, 06 Nov 1994 08:49:37 GMT

使用strftime不起作用,因为字符串是与语言环境相关的。我是否需要手工制作琴弦?

最佳答案

您可以从不依赖于语言环境设置的stdlib中使用wsgiref.handlers.format_date_time

from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime

now = datetime.now()
stamp = mktime(now.timetuple())
print format_date_time(stamp) #--> Wed, 22 Oct 2008 10:52:40 GMT

您可以使用不依赖于语言环境设置的stdlib中的email.utils.formatdate
from email.utils import formatdate
from datetime import datetime
from time import mktime

now = datetime.now()
stamp = mktime(now.timetuple())
print formatdate(
    timeval     = stamp,
    localtime   = False,
    usegmt      = True
) #--> Wed, 22 Oct 2008 10:55:46 GMT

如果您可以将语言环境设置为宽范围,则可以执行以下操作:
import locale, datetime

locale.setlocale(locale.LC_TIME, 'en_US')
datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')

如果您不想将语言环境设置为宽范围,则可以使用Babel date formating
from datetime import datetime
from babel.dates import format_datetime

now = datetime.utcnow()
format = 'EEE, dd LLL yyyy hh:mm:ss'
print format_datetime(now, format, locale='en') + ' GMT'

与wsgiref.handlers.format_date_time相同的手动格式化方法是:
def httpdate(dt):
    """Return a string representation of a date according to RFC 1123
    (HTTP/1.1).

    The supplied date must be in UTC.

    """
    weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
    month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
             "Oct", "Nov", "Dec"][dt.month - 1]
    return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
        dt.year, dt.hour, dt.minute, dt.second)

09-28 14:54