How to Change the time zone in Python logging?

前端 未结 7 1247
耶瑟儿~
耶瑟儿~ 2021-01-31 18:30

I would like to change the timestamp in the log file so that it reflects my current time zone so that i can debug errors at a faster rate,

is it possible that i can cha

7条回答
  •  一整个雨季
    2021-01-31 19:21

    If you know your utc offset, you can define a function to correct the time and then pass it to logging.Formatter.converter.

    For example, you want to convert the time to UTC+8 timezone, then:

    import logging
    import datetime
    
    
    def beijing(sec, what):
        '''sec and what is unused.'''
        beijing_time = datetime.datetime.now() + datetime.timedelta(hours=8)
        return beijing_time.timetuple()
    
    
    logging.Formatter.converter = beijing
    
    logging.basicConfig(
        format="%(asctime)s %(levelname)s: %(message)s",
        level=logging.INFO,
        datefmt="%Y-%m-%d %H:%M:%S",
    )
    

    Just change the hours in datetime.timedelta(hours=8) depending on your situation.

    Reference: https://alanlee.fun/2019/01/06/how-to-change-logging-date-timezone/

提交回复
热议问题