用两位数年份Python命名的打开文件

时间:2013-06-26 03:55:48

标签: python

我正在打开一个以下列格式命名的文件:

ex130626.log
exYYMMDD.log

以下代码需要4位数年份。如何获得像13这样的两位数年份?

today = datetime.date.today()
filename = 'ex{0}{1:02d}{2:02d}.log'.format(today.year, today.month, today.day)

3 个答案:

答案 0 :(得分:3)

只需采用年度模数:

>>> import datetime
>>> today = datetime.date.today()
>>> filename = 'ex{:02}{:02}{:02}.log'.format(today.year%100, today.month, today.day)
>>> filename
'ex130625.log'

但更简单的方法是strftime

>>> today.strftime('ex%y%m%d.log')
'ex130625.log'

答案 1 :(得分:3)

您可以使用strftime

filename = 'ex' + today.strftime("%y%m%d") + '.log'

答案 2 :(得分:0)

就像最后两个一样:

year = str(today.year)[-2:]
filename = 'ex{0}{1:02d}{2:02d}.log'.format(year, today.month, today.day)