python日期表示_RFC 1123 Python中的日期表示法?

Is there a fairly easy way to convert a datetime object into an RFC 1123 (HTTP/1.1) date/time string, i.e. a string with the format

Sun, 06 Nov 1994 08:49:37 GMT

Using strftime does not work, since the strings are locale-dependant. Do I have to build the string by hand?

解决方案

You can use wsgiref.handlers.format_date_time from the stdlib which does not rely on locale settings

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

You can use email.utils.formatdate from the stdlib which does not rely on locale settings

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

If you can set the locale process wide then you can do:

import locale, datetime

locale.setlocale(locale.LC_TIME, 'en_US')

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

If you don't want to set the locale process wide you could use 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'

A manual way to format it which is identical with wsgiref.handlers.format_date_time is:

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值