42

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")
vvvvv
  • 25,404
  • 19
  • 49
  • 81
dublintech
  • 16,815
  • 29
  • 84
  • 115
  • 1
    this was probably easily googled. – jdi Feb 03 '12 at 21:51
  • The title makes me laugh, luckily your question body is good or I would have no idea what "anyold anytime" means :) – Kekoa Feb 03 '12 at 21:53
  • 2
    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? – John Machin Feb 03 '12 at 21:58
  • 2
    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. – EML Feb 03 '12 at 22:18
  • 1
    Harsh. This question is much simpler and was voted up to 56. http://stackoverflow.com/questions/415511/how-to-get-current-time-in-python I also googled and was also wondering was there a smmarter way thant gettting a datetime and formatting it. – dublintech Feb 03 '12 at 22:29
  • 2
    Yes there is: use a `TimedRotatingFileHandler`! – Rik Poggi Feb 03 '12 at 22:34

7 Answers7

49

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'
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
  • 1
    I prefer an ISO-style date-time format as it makes sorting much easier. – johnsyweb Feb 03 '12 at 22:11
  • AttributeError: module 'datetime' has no attribute 'now' –  Jan 03 '19 at 15:20
  • 2
    @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? – johnsyweb Jan 04 '19 at 08:09
  • 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') – Ananda Prasad Bandaru Aug 31 '20 at 03:36
44

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'
Community
  • 1
  • 1
Rik Poggi
  • 28,332
  • 6
  • 65
  • 82
8

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

from datetime import datetime
print datetime.now().strftime("%d_%m_%Y")
Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
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}"
riggedCoinflip
  • 435
  • 4
  • 16
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...')
Brijesh Rana
  • 621
  • 7
  • 6
1
from time import strftime

fh = logging.FileHandler(strftime("mylogfile_%H_%M_%m_%d_%Y.log"))
eyquem
  • 26,771
  • 7
  • 38
  • 46
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")
Hamza Zafeer
  • 2,360
  • 13
  • 30
  • 42