How do you add datetime to a logfile name?
Asked Answered
F

7

44

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")
Fleurdelis answered 3/2, 2012 at 21:44 Comment(6)
this was probably easily googled.Somme
The title makes me laugh, luckily your question body is good or I would have no idea what "anyold anytime" means :)Hermelindahermeneutic
Wouldn't it be better to have filename in year, month, day etc order so that sorted directory listings weren't a pseudo-random jumble?Unclinch
On Stackoverflow, you're supposed to do research before posting a question. That being said, you ought to use: datetime.now().strftime('mylogfile_%Y-%m-%d_%H-%M') ... for more reasonable file ordering.Sulphur
Harsh. This question is much simpler and was voted up to 56. #416011 I also googled and was also wondering was there a smmarter way thant gettting a datetime and formatting it.Fleurdelis
Yes there is: use a TimedRotatingFileHandler!Blackman
N
51

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'
Nicety answered 3/2, 2012 at 21:48 Comment(4)
I prefer an ISO-style date-time format as it makes sorting much easier.Nicety
AttributeError: module 'datetime' has no attribute 'now'Kofu
@Sabrina I'm not sure that I understand your comment. Are you saying that you're getting this error on executing the line of code from my 7-year-old answer? Did you do something like import datetime rather than from datetime import datetime as in the question I was answering?Nicety
If you are getting an error like --AttributeError: module 'datetime' has no attribute 'now'-- Use --from datetime import datetime-- instead of --import datetime-- and then you can continue using logFileName = datetime.now().strftime('ALL_%H_%M_%d--%m_%Y.log')Catarina
B
46

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'
Blackman answered 3/2, 2012 at 21:51 Comment(2)
+1. Why reinvent the wheel when Python's already done such a great job!Nicety
I am not seeing any option through which we can generate a new file with timestamp each time program is run. Is there any way?Prudenceprudent
D
8

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

from datetime import datetime
print datetime.now().strftime("%d_%m_%Y")
Dorking answered 3/2, 2012 at 21:48 Comment(0)
I
3

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}"
Intitule answered 7/1, 2020 at 17:31 Comment(0)
V
2

We can use datetime.now() to get current timestamp. Here is my code that I am using to create log file with timestamp -

import logging
from datetime import datetime
LOG_FILENAME = datetime.now().strftime('D:/log/logfile_%H_%M_%S_%d_%m_%Y.log')
for handler in logging.root.handlers[:]:
      logging.root.removeHandler(handler)
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)    
logging.info('Forecastiong Job Started...')
logging.debug('abc method started...')
Varix answered 27/3, 2019 at 19:49 Comment(0)
P
1
from time import strftime

fh = logging.FileHandler(strftime("mylogfile_%H_%M_%m_%d_%Y.log"))
Portingale answered 4/2, 2012 at 2:50 Comment(0)
S
0

To print hour, minutes, day, month and year, use the following statement

from datetime import datetime

print datetime.now().strftime("%H_%M_%d_%m_%Y")
Sequence answered 19/2, 2018 at 11:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.