Search code examples
pythonpython-2.7iso8601

Python logger output dates in IS8601 format


Is there a way to make the Python logger output dates in ISO8601 format?

My logger is set up like this...

logging.basicConfig(
    format="%(message)s - %(asctime)s)

From the Python docs (located here: https://docs.python.org/2/howto/logging.html) you can see the following:

The default format for date/time display (shown above) is ISO8601. If you need more control over the formatting of the date/time, provide a datefmt argument to basicConfig, as in this example:

The only problem is that the date output is not ISO8601 format. The date output by the above formatter is:

2018-06-15 11:07:41,454

This is not ISO8601 format as defined here: https://en.wikipedia.org/wiki/ISO_8601

What is the easiest way to get the date in the correct format? Can this be done out of the box or do I need to import a package to do it?

I've tried adding a date formatter e.g. datefmt="%Y-%m-%dT%H:%M:%S.%f %Z" but some of the formatting characters were not recognised - namely %f and %Z gave a textual description of the timezone and not a numeric offset.


Solution

  • This works for me in most situations:

    logging.basicConfig(
        format="%(asctime)s %(message)s",
        datefmt="%Y-%m-%dT%H:%M:%S%z"
    )
    

    The output looks like:

    2019-11-09T01:18:13-0800 Something logged here

    Update:

    A one-liner I've been using to include miliseconds:

    logging.Formatter.formatTime = (lambda self, record, datefmt=None: datetime.datetime.fromtimestamp(record.created, datetime.timezone.utc).astimezone().isoformat(sep="T",timespec="milliseconds"))
    

    The output looks like

    2021-08-05T22:43:02.985614+00:00 Something logged here