How to Change the time zone in Python logging?

前端 未结 7 1243
耶瑟儿~
耶瑟儿~ 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:22

    #!/usr/bin/env python
    from datetime import datetime
    import logging
    import time
    
    from pytz import timezone, utc
    
    
    def main():
        logging.basicConfig(format="%(asctime)s %(message)s",
                            datefmt="%Y-%m-%d %H:%M:%S")
        logger = logging.getLogger(__name__)
        logger.error("default")
    
        logging.Formatter.converter = time.localtime
        logger.error("localtime")
    
        logging.Formatter.converter = time.gmtime
        logger.error("gmtime")
    
        def customTime(*args):
            utc_dt = utc.localize(datetime.utcnow())
            my_tz = timezone("US/Eastern")
            converted = utc_dt.astimezone(my_tz)
            return converted.timetuple()
    
        logging.Formatter.converter = customTime
        logger.error("customTime")
    
        # to find the string code for your desired tz...
        # print(pytz.all_timezones)
        # print(pytz.common_timezones)
    
    
    if __name__ == "__main__":
        main()
    
    • Ostensibly the pytz package is the blessed way of converting time zones in Python. So we start with datetime, convert, then get the (immutable) time_tuple to match return type of the time methods
    • Setting the logging.Formatter.converter function is recommended by this answer: (Python logging: How to set time to GMT).
    • Find your favorite TZ code by uncommenting the end lines

提交回复
热议问题