首先考虑date如何增加后缀1st,2nd,3rd, 4th
首先看笨办法:
from datetime import date d = date.today() benchmark = ['zilch', '1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th', '31st'] print(f'{d.strftime("%Y_%b")}_{benchmark[ int( d.strftime("%d") ) ]}')
这个很容易理解。
或者:
ordinaltg = lambda n: '{}{}'.format(n, {1: 'st', 2: 'nd', 3: 'rd'}.get(4 if 10 <= n % 100 < 20 else n % 10, "th")) #使用了dict的get method print([ordinaltg(n) for n in range(1,32)])
看个高级点的解决办法:
from datetime import date d = date(2012, 8, 17) ordinal = lambda n: f'{n}{"tsnrhtdd"[(n//10%10!=1)*(n%10<4)*n%10::4]}' #string slice [::-1] print(f'{d.strftime("%Y_%b")}_{ordinal(int(d.strftime("%d")))}')
source: https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement