Explain Codes LogoExplain Codes Logo

How to Customize the time format for Python logging?

python
logging
configuration
best-practices
Anton ShumikhinbyAnton Shumikhin·Jan 23, 2025
TLDR

For a quick fix, tweak your Python logging time format by adjusting the datefmt property in the Formatter. Use this handy code to set up a logger that generates messages stamped with a customized timestamp:

import logging # Our very own Avengers-worthy time stone format time_format = '%Y-%m-%d %H:%M:%S' # Assembled logger set to save the day! logger = logging.getLogger('super_logger') logger.setLevel(logging.INFO) handler = logging.StreamHandler() # Now the stones are your to command, make them sing! formatter = logging.Formatter('%(asctime)s - %(message)s', datefmt=time_format) handler.setFormatter(formatter) logger.addHandler(handler) # Feel the infinity stones at work? Bask in its glory! logger.info('Custom time format log')

Just switch up time_format with the strftime directive you prefer, and watch as your log records get a face lift. This setup ensures every log entry time-travels to a specific date and time.

Swift Logging Configuration

Keeping things quick and clean, the logging.basicConfig function can be used with the datefmt parameter, setting a uniform time format for your logs:

import logging # String up the time stone custom_time_format = '%Y-%m-%d %H:%M:%S' # Let the stone cast its spell across all logs logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt=custom_time_format) # And voila! Magic begets magic logging.info('This too, uses the custom time format')

This is a shortcut to glory when your logging configuration is simple, and you're looking for a mass effect.

Playing with fileConfig

When you're dealing with a heavier workload, multiple loggers, and a variation of handlers, it's easier and neater to define your time formats within a configuration file. It keeps your code uncluttered and manageable:

[formatter_myFormatter] format=%(asctime)s - %(levelname)s - %(message)s datefmt=%Y-%m-%d %H:%M:%S

This way, you can reference the formatter that suits you best in your loggers' configurations.

Time Elements Tailor-made

With strftime directives like %Y for the year, %m for the month, %d for the day, %H for the 24-hour, and %I for the 12-hour format, you’re the master of time.

Millisec? Nah!

Lost in milliseconds (%f) that you'd love to get rid off? Simply drop %f from your datefmt string, and you're home free!

logging.Formatter('%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')

Flexi-time with Dynamic Formatters

Creating custom formatters on-the-go allows you to assign different timestamps to different handlers or loggers. This makes sense when you're dealing with diverse formats within the same application.

# Formatter for console handler - because who has time for milliseconds anyway? console_formatter = logging.Formatter('%(asctime)s - %(message)s', '%H:%M:%S') # Formatter for file handler - let's track those microseconds! file_formatter = logging.Formatter('%(asctime)s - %(message)s', '%H:%M:%S.%f')

Now the level of details in your logs don't have to be uniform everywhere. You have the power to direct.