How to set timestamps on GMT/UTC on Python logging?

Question:

Is it possible and how to set the logging timezone to GMT?

(i.e. the %(asctime)s parameter in the format)

Asked By: Jonathan Livni

||

Answers:

logging.Formatter.converter = time.gmtime

(documented in the docstring of logging.Formatter.formatTime)

Answered By: Sven Marnach

Just setting logging.Formatter.converter = time.gmtime is ineffective for me in Python 2.5.

So I created a child class with it set, and use that in place of logging.Formatter:

class UTCFormatter(logging.Formatter):
    converter = time.gmtime
Answered By: rakslice

I’ve had problems with both of these answers. So I just changed global timezone for the whole script:

os.environ['TZ'] = 'Europe/London'
time.tzset()
Answered By: dijxtra

Here is code example:

import logging, logging.handlers
import time

logit = logging.getLogger('logit')
handler = logging.handlers.RotatingFileHandler("file.log", maxBytes=20000, backupCount=5)
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(levelname)8s: %(message)s')
handler.setFormatter(formatter)
logging.Formatter.converter = time.gmtime
logit.addHandler(handler)

logit.info("test log message")

Output:

2019-11-14 16:34:22,967     INFO: test log message
Answered By: Vlad Gulin

From the python 3 docs:

import time

class UTCFormatter(logging.Formatter):
    converter = time.gmtime

https://docs.python.org/3/howto/logging-cookbook.html#formatting-times-using-utc-gmt-via-configuration

Answered By: dcordz

This works:

os.environ['TZ'] = 'UTC'
time.tzset()

But does change the TZ environment for the whole process and any sub-processes. Not necessarily a bad thing, but something to be aware of before doing this.

Alternately if you set the TZ environment variable from outside (whether just in whatever runs the python, or at a whole system level) before you run python, that also works.

Answered By: thorfi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.