How to Customize the time format for Python logging?

Better Stack Team
Updated on August 25, 2023

To customize the time format for Python logging, you need to modify the formatter used by the logging module. Python's logging module provides a powerful mechanism to control the log message formatting, including the timestamp format. You can use the logging.Formatter class to create a custom formatter and set it to the desired time format.

The time format follows the same syntax as the time.strftime() function, where you can use specific placeholders for different components of the timestamp, such as year, month, day, hour, minute, second, etc.

Here's an example of how to customize the time format for Python logging:

import logging

# Create a custom formatter with your desired time format
time_format = "%Y-%m-%d %H:%M:%S"
formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s', datefmt=time_format)

# Create a logger and set the custom formatter
logger = logging.getLogger('custom_logger')
handler = logging.StreamHandler()

# Set the log level (optional, can be DEBUG, INFO, WARNING, ERROR, CRITICAL)

# Now you can use the logger to log messages with your custom time format
logger.debug('This is a debug message')'This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')

In this example, the time_format variable is set to "%Y-%m-%d %H:%M:%S", which will produce a timestamp in the format "YYYY-MM-DD HH:MM:SS".

The logging.Formatter class takes two arguments: fmt for the log message format (including placeholders for the timestamp), and datefmt for the custom time format.

By using this approach, you can easily customize the time format according to your preference and requirements. The logging module will then use your custom formatter to format the log messages, including the timestamp, based on the specified time format.

To learn more about logging in Python, visit Better Stack Community.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →