Python中的RFC 1123date表示?

有没有一种相当简单的方法来将date时间对象转换为RFC 1123(HTTP / 1.1)date/时间string,即具有格式的string

Sun, 06 Nov 1994 08:49:37 GMT 

使用strftime不起作用,因为string是依赖于语言环境的。 我是否必须手工制作string?

您可以使用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格式化

 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提供了一个函数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()) 

您可以设置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)