您的位置:首頁技術文章
文章詳情頁

使用python strftime顯示日期,例如“ May 5th”。

瀏覽:2日期: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”)。做這個的最好方式是什么?

標簽: Python 編程
国产综合久久一区二区三区