【问题标题】:How can I log the current time with timezone in Python?如何在 Python 中使用时区记录当前时间?
【发布时间】:2018-09-19 21:40:48
【问题描述】:

我使用具有以下格式化程序的日志记录配置(YAML 文件):

formatters:
    detailed:
        class: logging.Formatter
        format: '[%(asctime)s]:[%(levelname)s]: %(message)s'

asctime 提供类似2018-04-10 07:00:39,526 的字符串,但我也想获取当前时区,例如2018-04-10 07:00:39,526+02:00。如果没有work-around from Python 2.X,这可能吗?

【问题讨论】:

    标签: python-3.x logging timezone


    【解决方案1】:

    您可以创建一个自定义日志记录类,如下所示:

    import logging
    class FormatterWithTimezone(logging.Formatter):
        def formatTime(self, record, datefmt=None):
            return (
                time.strftime('%Y-%m-%d %H:%M:%S,%%03d%z', self.converter(record.created))
                % record.msecs)
    

    然后设置这个类来代替logging.Formatter。

    【讨论】:

      猜你喜欢
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      相关资源
      最近更新 更多