How do you add datetime to a logfile name?

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")

Another Solution using format():

#generates a date for a generic filename
import datetime
date_raw = datetime.datetime.now()
date_processed = "{}-{}-{}_{}-{}-{}".format(date_raw.year, date_raw.month, 
                  date_raw.day, date_raw.hour, date_raw.minute, date_raw.second)
#example value: date_processed = 2020-1-7_17-17-48

I used this in my own project
edit: as I found out about f(ormatted)-strings, this would be another solution:

date_processed = f"{date_raw.year}-{date_raw.month}-{date_raw.day}_{date_raw.hour}-{date_raw.minute}-{date_raw.second}"

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'

Tags:

Python

Logging