栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python日志记录:使用毫秒格式的时间

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python日志记录:使用毫秒格式的时间

请注意,[ 克雷格·麦克丹尼尔(CraigMcDaniel)的解决方案显然更好。

这也应该工作:

logging.Formatter(fmt='%(asctime)s.%(msecs)03d',datefmt='%Y-%m-%d,%H:%M:%S')

logging.Formatter的

formatTime
方法如下所示:

def formatTime(self, record, datefmt=None):    ct = self.converter(record.created)    if datefmt:        s = time.strftime(datefmt, ct)    else:        t = time.strftime("%Y-%m-%d %H:%M:%S", ct)        s = "%s,%03d" % (t, record.msecs)    return s

请注意中的逗号

"%s,%03d"
。不能通过指定a来解决此问题,
datefmt
因为
ct
a是,
time.struct_time
并且这些对象不记录毫秒。

如果我们更改的定义

ct
以使其成为
datetime
对象而不是
struct_time
,那么(至少在现代版本的Python中)可以调用
ct.strftime
,然后可以用来
%f
设置微秒的格式:

import loggingimport datetime as dtclass MyFormatter(logging.Formatter):    converter=dt.datetime.fromtimestamp    def formatTime(self, record, datefmt=None):        ct = self.converter(record.created)        if datefmt: s = ct.strftime(datefmt)        else: t = ct.strftime("%Y-%m-%d %H:%M:%S") s = "%s,%03d" % (t, record.msecs)        return slogger = logging.getLogger(__name__)logger.setLevel(logging.DEBUG)console = logging.StreamHandler()logger.addHandler(console)formatter = MyFormatter(fmt='%(asctime)s %(message)s',datefmt='%Y-%m-%d,%H:%M:%S.%f')console.setFormatter(formatter)logger.debug('Jackdaws love my big sphinx of quartz.')# 2011-06-09,07:12:36.553554 Jackdaws love my big sphinx of quartz.

或者,要获得毫秒数,请将逗号更改为小数点,然后省略

datefmt
参数:

class MyFormatter(logging.Formatter):    converter=dt.datetime.fromtimestamp    def formatTime(self, record, datefmt=None):        ct = self.converter(record.created)        if datefmt: s = ct.strftime(datefmt)        else: t = ct.strftime("%Y-%m-%d %H:%M:%S") s = "%s.%03d" % (t, record.msecs)        return s...formatter = MyFormatter(fmt='%(asctime)s %(message)s')...logger.debug('Jackdaws love my big sphinx of quartz.')# 2011-06-09 08:14:38.343 Jackdaws love my big sphinx of quartz.


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/638804.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号