带毫秒或微秒和时区偏移的日期时间

wim*_*wim 2 python logging timezone datetime python-3.x

这是日期所需的表示形式:

>>> tz = pytz.timezone('US/Central')
>>> datefmt = '%Y-%m-%d %H:%M:%S.%f%z(%Z)'
>>> datetime.now(tz).strftime(datefmt)
'2017-04-27 15:09:59.606921-0500(CDT)'
Run Code Online (Sandbox Code Playgroud)

这是它的记录方式(Linux 上的 Python 3.6.0):

>>> logrecord_format = '%(asctime)s %(levelname)s %(message)s'
>>> logging.basicConfig(format=logrecord_format, datefmt=datefmt)
>>> logging.error('ruh-roh!')
2017-04-27 15:10:35.%f-0500(CDT) ERROR ruh-roh!
Run Code Online (Sandbox Code Playgroud)

它没有正确填充微秒。我已经尝试将 更改为logrecord_format其他一些东西,但我无法弄清楚 - 如何配置记录器以正确的方式显示微秒和时区以strftime完全匹配输出?


编辑 我可以用偏移量解决毫秒,即2017-04-27 15:09:59,606-0500(CDT)。那可能吗? logging提供%(msecs)03d指令,但我似乎无法让时区偏移出现毫秒之后。

Del*_*gan 6

就个人而言,我没有将时区集成到日期格式中,而是直接将其添加到记录的消息格式中。通常,时区在程序执行期间不应更改。

import logging
import time

tz = time.strftime('%z')
fmt = '%(asctime)s' + tz + ' %(levelname)s %(message)s'

logging.basicConfig(format=fmt)

logging.error("This is an error message.")

# 2017-07-28 19:34:53,336+0200 ERROR This is an error message.
Run Code Online (Sandbox Code Playgroud)