日期时间,以毫秒或微秒为单位,时区偏移量

时间:2017-04-27 20:15:46

标签: python python-3.x datetime logging timezone

这是日期所需的表示:

>>> 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)'

这是它的记录方式(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!

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

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

1 个答案:

答案 0 :(得分:3)

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

Dates