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
#!/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()
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
methodslogging.Formatter.converter
function is recommended by this answer: (Python logging: How to set time to GMT).