如何使用Python的strftime显示日期,如“5月5日”?
可能重复的问题:
Python: 日期序数输出?
在Python中,time.strftime可以很简单地输出像“星期四 五月 05”这样的字符串,但我想生成一个像“星期四 五月 5th”这样的字符串(注意日期后面多了一个“th”)。有什么好的方法可以做到这一点呢?
5 个回答
12
"%s%s"%(day, 'trnshddt'[0xc0006c000000006c>>2*day&3::4])
不过说真的,这个是跟地区有关的,所以你应该在进行国际化的时候处理这个问题。
19
这段代码看起来可以添加合适的后缀,并且去掉日期中难看的前导零。
#!/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())
103
strftime
这个函数不支持在日期后面加上后缀,比如“st”、“nd”、“rd”或“th”。
不过,这里有一种方法可以得到正确的后缀:
if 4 <= day <= 20 or 24 <= day <= 30:
suffix = "th"
else:
suffix = ["st", "nd", "rd"][day % 10 - 1]
更新:
结合了一个更简洁的解决方案,基于 Jochen 的评论和 gsteff 的回答:
from datetime import datetime as dt
def suffix(d):
return {1:'st',2:'nd',3:'rd'}.get(d%20, '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())
结果是:
2011年5月5日