Want datetime in logfile name

When I create my logfile, I want the name to contain the datetime.

Now, in python you can get the current datetime as:

>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2012, 2, 3, 21, 35, 9, 559000)

The str version is

>>> str(datetime.now())
'2012-02-03 21:35:22.247000'

Not a very nice str to append to the logfile name! I would like my logfile to be something like:

mylogfile_21_35_03_02_2012.log

Is there something python can to do to make this easy to do? note, I am creating the log file as

fh = logging.FileHandler("mylogfile" + datetimecomp + ".log")

Any tips?


You need datetime.strftime() , this allows you to format the timestamp using all of the directives of C's strftime() . In your specific case:

>>> datetime.now().strftime('mylogfile_%H_%M_%d_%m_%Y.log')
'mylogfile_08_48_04_02_2012.log'

You could also use a TimedRotatingFileHandler that will handle the date and the rollover every day (or whenever you want) for you.

from logging.handlers import TimedRotatingFileHandler
fh = TimedRotatingFileHandler('mylogfile',  when='midnight')

By default the format will be depending on the rollover interval:

The system will save old log files by appending extensions to the filename. The extensions are date-and-time based, using the strftime format %Y-%m-%d_%H-%M-%S or a leading portion thereof, depending on the rollover interval.

But you can modify that as showed here, by doing something like:

from logging.handlers import TimedRotatingFileHandler
fh = TimedRotatingFileHandler('mylogfile',  when='midnight')
fh.suffix = '%Y_%m_%d.log'

Yes. Have a look at the datetime API, in particular strftime .

from datetime import datetime
print datetime.now().strftime("%d_%m_%Y")
链接地址: http://www.djcxy.com/p/40916.html

上一篇: Python在正确的时区获得当前时间

下一篇: 想要日志文件名称中的日期时间