In Python, it can be very useful to add a timestamp when logging information to the console. We can log the timestamp to the console with the logging module easily by adjusting the basic configuration.

import logging

logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S')

logging.info('Message for the user.')

#Output:
2022-01-25 07:58:28 INFO     Message for the user.

The logging module is very useful for developers to add logging calls in their code to print messages to the console when certain messages occur.

Many times, a simple message is not enough, and we want to add time to our logging messages.

We can easily add timestamps to our logging messages by changing the basic configuration of the logging module.

Below is some sample code for you to see how you can use the basicConfig property of the logging module to change the message format and add the timestamp.

import logging

logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S')

logging.info('Message for the user.')

#Output:
2022-01-25 07:58:28 INFO     Message for the user.

Printing the Current Time To Console Without Logging Module

If you are just trying to print the current time to the console, and you are not using the logging module, you can do so easily in Python with the datetime module.

To get the current timestamp and print it to the console, we use the now() and timestamp() functions from the datetime module.

Below is the code you can use to print the current time to the console using Python.

import datetime
  
current_time = datetime.datetime.now()
timestamp_of_current_time = current_time.timestamp()

print(timestamp_of_current_time)

#Output:
1644352484.462

Hopefully this article has been useful for you to learn how to use the logging module to add the timestamp to your logging messages.

Categorized in:

Python,

Last Update: February 26, 2024