UPDATE:
The original question seems invalid as even if I managed to force logger to use datetime.now()
, it still does not solve my ultimate goal of making the logging timestamps responsive to OS timezone changes without restarting the python interpreter. I have provided the answer I found below.
How to force the logger to use datetime.now()
instead of time.asctime()
? I need the log to follow strictly the Windows OS provided time, but time.asctime()
attempts to convert the timezone if it thinks is needed. How do I override this behaviour?
Currently i use a custom logging.format subclass with the format string '{asctime}: {levelname} - {message}'
The purpose of doing this is because my python script changes the OS timezone during the execution. I want the log to immediately follow the updated timezone right after the script changes it. I have tried to define a converter
function inside the logging.format
subclass, but that resulted in the timezone in the logs not being updated even after I changed it.
The code I used (from doc https://docs.python.org/3.9/library/logging.html#logging.Formatter.formatTime):
class custom(logging.Formatter):
def converter(self, timestamp):
return datetime.now()
Tried every single answer from here: How to Change the time zone in Python logging?, non works as they all do not update to the new timezone set in the OS by my script. I tried to importlib.reload(tzlocal)
and also no use.
The only sensible answer I found was to use time.tzset()
but it apparently is not available on Windows