RFC 1123 Python中的日期表示?

时间:2008-10-22 09:59:22

标签: python http datetime

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

的字符串
Sun, 06 Nov 1994 08:49:37 GMT

使用strftime不起作用,因为字符串依赖于语言环境。我必须手工构建字符串吗?

5 个答案:

答案 0 :(得分:84)

您可以使用不依赖于区域设置的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)

答案 1 :(得分:35)

您可以使用Python标准电子邮件模块中的formatdate()函数:

from email.utils import formatdate
print formatdate(timeval=None, localtime=False, usegmt=True)

以所需格式提供当前时间:

Wed, 22 Oct 2008 10:32:33 GMT

实际上,这个函数在不使用strftime()

的情况下“手动”完成

答案 2 :(得分:9)

如果有人正在阅读 Django 项目,那么Django会提供一个函数django.utils.http.http_date(epoch_seconds)

from django.utils.http import http_date

some_datetime = some_object.last_update
response['Last-Modified'] = http_date(some_datetime.timestamp())

答案 3 :(得分:1)

您可以设置LC_TIME以强制stftime()使用特定的区域设置:

>>> locale.setlocale(locale.LC_TIME, 'en_US')
'en_US'
>>> datetime.datetime.now().strftime(locale.nl_langinfo(locale.D_T_FMT))
'Wed 22 Oct 2008 06:05:39 AM '

答案 4 :(得分:1)

嗯,这是一个手动函数来格式化它:

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)