有没有一种相当简单的方法可以将日期时间对象转换为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 日期格式
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)
您可以使用 Python 标准电子邮件模块中的 formatdate() 函数:
from email.utils import formatdate
print formatdate(timeval=None, localtime=False, usegmt=True)
以所需格式提供当前时间:
Wed, 22 Oct 2008 10:32:33 GMT
事实上,这个函数"手动"完成,而不使用 strftime()
如果有人正在阅读本文,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())
此函数使用email.utils.formatdate
,这相当于:
from email.utils import formatdate
response['Last-Modified'] = formatdate(some_datetime.timestamp(), usegmt=True)
你可以设置 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 '
好吧,这是一个手动函数来格式化它:
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)