可能的重复:
Python:日期顺序输出? https://stackoverflow.com/questions/739241/python-date-ordinal-output
在Python中,time.strftime可以很容易地生成像“Thursday May 05”这样的输出,但我想生成一个像“Thursday May 5th”这样的字符串(注意日期上的附加“th”)。做这个的最好方式是什么?
strftime
不允许您使用后缀格式化日期。
这是获取正确后缀的方法:
if 4 <= day <= 20 or 24 <= day <= 30:
suffix = "th"
else:
suffix = ["st", "nd", "rd"][day % 10 - 1]
在这里找到 http://snipplr.com/view/3468/python-date-suffixes-for-strftime/
Update:
将基于 Jochen 评论的更紧凑的解决方案与格斯特夫的回答 https://stackoverflow.com/questions/5891555/display-the-date-like-may-5th-using-pythons-strftime/5891658#5891658:
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())
Gives:
May 5th, 2011
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)