如何解决使用python strftime显示日期,例如“ May 5th”
strftime
不允许您使用后缀格式化日期。
这是获取正确后缀的方法:
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 '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())
给出:
May 5th, 2011
解决方法
在Python中,time.strftime可以很容易地产生类似“ Thursday May 05”的输出,但是我想生成一个类似“ Thursday May
5th”的字符串(注意日期上的附加“ th”)。做这个的最好方式是什么?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。