Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add datetime to a logfile name?

Tags:

python

logging

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

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 do to make this easy? I am creating the log file as:

fh = logging.FileHandler("mylogfile" + datetimecomp + ".log") 
like image 357
dublintech Avatar asked Feb 03 '12 21:02

dublintech


People also ask

How do you put date and time in a file name?

I'd use YYYY-MM-DD HHmmss for filenames, unless there is a particular need for timezones or a possible need to parse them into ISO dates; in those cases an ISO date would probably be preferrable.

What does datetime datetime NOW () do?

now() function Return the current local date and time, which is defined under datetime module.


2 Answers

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' 
like image 135
Johnsyweb Avatar answered Sep 28 '22 09:09

Johnsyweb


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' 
like image 34
Rik Poggi Avatar answered Sep 28 '22 08:09

Rik Poggi