Skip to content

Instantly share code, notes, and snippets.

@daaniam
Last active June 2, 2024 22:44
Show Gist options
  • Save daaniam/041bfd34c1d14e5aeb1bf84537b47fb6 to your computer and use it in GitHub Desktop.
Save daaniam/041bfd34c1d14e5aeb1bf84537b47fb6 to your computer and use it in GitHub Desktop.
Python logging time (microseconds with timezone)
# Basic configuration
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(name)s - %(funcName)20s() on line %(lineno)s - %(message)s",
# datefmt="%Y-%m-%d %H:%M:%S.%f %Z%z",
handlers=[stream_handler],
)
def _format_logging_time(self, record, datefmt: str = None) -> str:
"""Return time for logging with microseconds and timezone. datefmt is ignored."""
# Local timezone - example: 2022-06-02T14:51:25.367718-07:00
# local_time = datetime.fromtimestamp(record.created).astimezone().isoformat()
# UTC time - example: 2022-06-02T21:54:19.878140+00:00
utc_time = datetime.fromtimestamp(record.created, tz=timezone.utc).isoformat()
return str(utc_time)
logging.Formatter.formatTime = _format_logging_time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment