Skip to content

Instantly share code, notes, and snippets.

@vernomcrp
Created May 14, 2018 09:31
Show Gist options
  • Select an option

  • Save vernomcrp/18069053fb3cf3807c9e8601eb8016d5 to your computer and use it in GitHub Desktop.

Select an option

Save vernomcrp/18069053fb3cf3807c9e8601eb8016d5 to your computer and use it in GitHub Desktop.
Python logging example showing a minimal way to add support for timezone (%z) and milliseconds (%f) format strings for time.strftime without datetime, pytz, etc. Raw
# Quick Python logging example. Shows a minimal way to support timezone (%z)
# and milliseconds (%f) format strings in a logging formatter's datefmt string.
# The default Formatter.formatTime func loses timezone info (%z becomes +0000)
# because time.strtime is passed struct_time from time.localtime(rec.created).
# Calling time.strftime('%z') without passing an explicit struct_time yields a
# string based on the system's timezone at call time, which is good enough.
import time
import sys
import logging
class Formatter(logging.Formatter):
def formatTime(self, record, datefmt=None):
ct = self.converter(record.created)
if datefmt:
# support %z and %f in datefmt (struct_time doesn't carry ms or tz)
datefmt = datefmt.replace("%f", "%03d" % int(record.msecs))
datefmt = datefmt.replace('%z', time.strftime('%z'))
s = time.strftime(datefmt, ct)
else:
t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
s = "%s,%03d" % (t, record.msecs)
return s
# usage
console = logging.StreamHandler(sys.stdout)
console.setFormatter(
Formatter("%(asctime)s %(message)s", "%a, %d %b %Y %H:%M:%S.%f %z"))
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
log.addHandler(console)
log.info("Check out this RFC 2822 format date and time logged, yo!")
@bukowa
Copy link
Copy Markdown

bukowa commented Feb 10, 2023

    def formatTime(self, record, datefmt=None) -> str:
        return datetime.fromtimestamp(record.created).strftime(datefmt or self.datefmt)

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