2

I'm opening a file named in the following format :

ex130626.log
exYYMMDD.log

following code wants 4-digit year. How to get the two digit year like 13?

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

3 回答 3

4

只需取年的模数:

>>> 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'
于 2013-06-26T03:58:45.417 回答
3

您可以使用strftime

filename = 'ex' + today.strftime("%y%m%d") + '.log'
于 2013-06-26T04:00:02.830 回答
0

只需像这样取最后两个:

year = str(today.year)[-2:]
filename = 'ex{0}{1:02d}{2:02d}.log'.format(year, today.month, today.day)
于 2013-06-26T03:57:49.117 回答