使用python strftime顯示日期,例如“ May 5th”。
strftime 不允許您使用后綴格式化日期。
這是獲取正確后綴的方法:
if 4 <= day <= 20 or 24 <= day <= 30: suffix = 'th'else: suffix = ['st', 'nd', 'rd'][day % 10 - 1]更新:
將基于Jochen的評(píng)論的更緊湊的解決方案與gsteff的答案相結(jié)合:
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可以很容易地產(chǎn)生類(lèi)似“ Thursday May 05”的輸出,但是我想生成一個(gè)類(lèi)似“ Thursday May5th”的字符串(注意日期上的附加“ th”)。做這個(gè)的最好方式是什么?
