Python IS8601 格式的记录器输出日期
Python logger output dates in IS8601 format
有没有办法使 Python 记录器输出日期为 ISO8601 格式?
我的记录器是这样设置的...
logging.basicConfig(
format="%(message)s - %(asctime)s)
从 Python 文档(位于此处:https://docs.python.org/2/howto/logging.html)您可以看到以下内容:
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:
唯一的问题是日期输出不是 ISO8601 格式。上述格式器输出的日期为:
2018-06-15 11:07:41,454
这不是此处定义的 ISO8601 格式:https://en.wikipedia.org/wiki/ISO_8601
获取格式正确的日期的最简单方法是什么?这可以开箱即用,还是我需要导入一个包才能完成?
我试过添加日期格式化程序,例如datefmt="%Y-%m-%dT%H:%M:%S.%f %Z"
但一些格式字符无法识别 - 即 %f
和 %Z
给出了时区的文本描述,而不是数字偏移量。
这在大多数情况下对我有用:
logging.basicConfig(
format="%(asctime)s %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S%z"
)
输出如下:
2019-11-09T01:18:13-0800 Something logged here
更新:
我一直用来包含毫秒的单行代码:
logging.Formatter.formatTime = (lambda self, record, datefmt=None: datetime.datetime.fromtimestamp(record.created, datetime.timezone.utc).astimezone().isoformat(sep="T",timespec="milliseconds"))
输出看起来像
2021-08-05T22:43:02.985614+00:00 Something logged here
有没有办法使 Python 记录器输出日期为 ISO8601 格式?
我的记录器是这样设置的...
logging.basicConfig(
format="%(message)s - %(asctime)s)
从 Python 文档(位于此处:https://docs.python.org/2/howto/logging.html)您可以看到以下内容:
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:
唯一的问题是日期输出不是 ISO8601 格式。上述格式器输出的日期为:
2018-06-15 11:07:41,454
这不是此处定义的 ISO8601 格式:https://en.wikipedia.org/wiki/ISO_8601
获取格式正确的日期的最简单方法是什么?这可以开箱即用,还是我需要导入一个包才能完成?
我试过添加日期格式化程序,例如datefmt="%Y-%m-%dT%H:%M:%S.%f %Z"
但一些格式字符无法识别 - 即 %f
和 %Z
给出了时区的文本描述,而不是数字偏移量。
这在大多数情况下对我有用:
logging.basicConfig(
format="%(asctime)s %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S%z"
)
输出如下:
2019-11-09T01:18:13-0800 Something logged here
更新:
我一直用来包含毫秒的单行代码:
logging.Formatter.formatTime = (lambda self, record, datefmt=None: datetime.datetime.fromtimestamp(record.created, datetime.timezone.utc).astimezone().isoformat(sep="T",timespec="milliseconds"))
输出看起来像
2021-08-05T22:43:02.985614+00:00 Something logged here