Skip to content

Instantly share code, notes, and snippets.

@hartwork
Created May 5, 2025 15:18
Show Gist options
  • Save hartwork/8b5963b5e9a698a3d6d352c657418af3 to your computer and use it in GitHub Desktop.
Save hartwork/8b5963b5e9a698a3d6d352c657418af3 to your computer and use it in GitHub Desktop.
Demo Python logging with time zone information for field `asctime`
#! /usr/bin/env python3
# Copyright (c) Sebastian Pipping <[email protected]>
#
# Licensed under Zero-Clause BSD
# SPDX-License-Identifier: 0BSD
import datetime
import logging
class CustomFormatter(logging.Formatter):
def formatTime(self, record, datefmt=None):
local_time_zone = datetime.datetime.now().astimezone().tzinfo
dt = datetime.datetime.fromtimestamp(record.created, tz=local_time_zone)
return dt.isoformat(sep=" ", timespec="milliseconds")
format_ = "[%(asctime)s][%(levelname)s] %(message)s"
logging.basicConfig(format=format_)
logging.warning("First warning, no time zone")
# Now install customer formatter class
formatter = CustomFormatter(fmt=format_)
for handler in logging.root.handlers:
handler.setFormatter(formatter)
logging.warning("Second warning, with time zone")
@hartwork
Copy link
Author

hartwork commented May 5, 2025

Output:

# python3 timezone_logging_demo.py 
[2025-05-05 17:15:08,341][WARNING] First warning, no time zone
[2025-05-05 17:15:08.341+02:00][WARNING] Second warning, with time zone

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment