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

PythonLoggingTimezoneUtc

Python Problem Overview


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

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

Python Solutions


Solution 1 - Python

logging.Formatter.converter = time.gmtime

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

Solution 2 - Python

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

Solution 3 - Python

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

Solution 4 - Python

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

Solution 5 - Python

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.

Solution 6 - Python

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()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonathan LivniView Question on Stackoverflow
Solution 1 - PythonSven MarnachView Answer on Stackoverflow
Solution 2 - PythonraksliceView Answer on Stackoverflow
Solution 3 - PythondcordzView Answer on Stackoverflow
Solution 4 - PythonVlad GulinView Answer on Stackoverflow
Solution 5 - PythonthorfiView Answer on Stackoverflow
Solution 6 - PythondijxtraView Answer on Stackoverflow