【问题标题】:Datetime with milliseconds or microseconds AND timezone offset具有毫秒或微秒和时区偏移的日期时间
【发布时间】:2017-04-27 20:15:46
【问题描述】:

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

>>> 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 指令,但我似乎无法让时区偏移出现在毫秒之后

【问题讨论】:

  • It looks like logging uses time.strftime 而不是datetime.datetime.strftime,并且time.strftime 不支持微秒(或毫秒,因此他们使用一种奇怪的技巧将它们添加到默认格式中)。
  • 如果你想这样做,你必须编写你自己的Formatter子类,以不同的方式实现formatTime
  • time.strftime 在我的平台上确实支持微秒:datetime.now().time().strftime('%H:%M:%S.%f') --> '15:42:54.516274'
  • time.strftimetime 模块中的strftime 函数一样,而不是datetime.time.strftime
  • 他们不一样?哦。 WTF。

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


【解决方案1】:

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

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.

【讨论】:

  • 避免子类化的巧妙方法 - 虽然不支持微秒
猜你喜欢
  • 1970-01-01
  • 2022-06-13
  • 2012-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-08
  • 1970-01-01
相关资源
最近更新 更多