文章详情页
使用python strftime显示日期,例如“ May 5th”。
浏览:3日期:2022-08-07 11:11:26
如何解决使用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 dtdef 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 May5th”的字符串(注意日期上的附加“ th”)。做这个的最好方式是什么?
排行榜
