可能重复:
Python:日期序数输出?
在Python中,time.strftime可以很容易地产生类似"星期四5月05"的输出,但是我想生成一个像"星期四5月5日"这样的字符串(注意日期的附加"th").做这个的最好方式是什么?
Aco*_*orn 58
strftime 不允许您使用后缀格式化日期.
这是获得正确后缀的方法:
if 4 <= day <= 20 or 24 <= day <= 30:
suffix = "th"
else:
suffix = ["st", "nd", "rd"][day % 10 - 1]
Run Code Online (Sandbox Code Playgroud)
结合基于Jochen评论的更紧凑的解决方案和gsteff的答案:
from datetime import datetime as dt
def suffix(d):
return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th')
def custom_strftime(format, t):
return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day))
print custom_strftime('%B {S}, %Y', dt.now())
Run Code Online (Sandbox Code Playgroud)
得到:
May 5th, 2011
gst*_*eff 14
这似乎添加了适当的后缀,并删除了天数中丑陋的前导零:
#!/usr/bin/python
import time
day_endings = {
1: 'st',
2: 'nd',
3: 'rd',
21: 'st',
22: 'nd',
23: 'rd',
31: 'st'
}
def custom_strftime(format, t):
return time.strftime(format, t).replace('{TH}', str(t[2]) + day_endings.get(t[2], 'th'))
print custom_strftime('%B {TH}, %Y', time.localtime())
Run Code Online (Sandbox Code Playgroud)
"%s%s"%(day, 'trnshddt'[0xc0006c000000006c>>2*day&3::4])
Run Code Online (Sandbox Code Playgroud)
但严重的是,这是特定于语言环境的,因此您应该在国际化期间这样做
| 归档时间: |
|
| 查看次数: |
18753 次 |
| 最近记录: |