How do you add datetime to a logfile name?

后端 未结 7 635
孤街浪徒
孤街浪徒 2020-12-29 19: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 da         


        
相关标签:
7条回答
  • 2020-12-29 19:58
    from time import strftime
    
    fh = logging.FileHandler(strftime("mylogfile_%H_%M_%m_%d_%Y.log"))
    
    0 讨论(0)
  • 2020-12-29 19:59

    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}"
    
    0 讨论(0)
  • 2020-12-29 20:05

    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'
    
    0 讨论(0)
  • 2020-12-29 20:05

    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'
    
    0 讨论(0)
  • 2020-12-29 20:06

    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...')
    
    0 讨论(0)
  • 2020-12-29 20:14

    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")
    
    0 讨论(0)
提交回复
热议问题