Python 使用tzoffset记录时间戳

Python 使用tzoffset记录时间戳,python,logging,Python,Logging,我正在使用python日志模块记录消息。我需要在日志文件中使用以下类型的日期格式化程序。我该怎么做 2016-11-29T06:12:59.519908+05:00 Year-Month-DateTHour:Min:Sec.microsec+timezone 目前我正在使用这个 formatter = logging.Formatter('%(asctime)s.%(msecs)06d %(levelname)s %(message)s',datefmt='%Y-%m-%dT%H:%M:%S

我正在使用python日志模块记录消息。我需要在日志文件中使用以下类型的日期格式化程序。我该怎么做

2016-11-29T06:12:59.519908+05:00

Year-Month-DateTHour:Min:Sec.microsec+timezone
目前我正在使用这个

formatter = logging.Formatter('%(asctime)s.%(msecs)06d %(levelname)s %(message)s',datefmt='%Y-%m-%dT%H:%M:%S')
这将产生以下结果:

2017-01-23T01:50:23.000606

我无法添加时区信息。

这里的问题是处理毫秒,因为在指定格式时处理方式不同

我们需要子类化
logging.Formatter
来覆盖
formatTime
方法,并像函数一样从record.msecs中获取毫秒数

此代码输出:

2017-01-23 13:45:42.466178+02:00 - root - ERROR - something bad!
更新 另一个问题是日志记录不使用
datetime
,而是使用没有时区的
time\u-struct
,因此在上面更新的代码中,我将对象从
time\u-struct
转换为datetime(可能会降低性能)


应从外部提供时区,因为日志记录不包含时区。

缺少正确的时区,+0000不是正确的时区,输出与我需要的不匹配。
2017-01-23 13:45:42.466178+02:00 - root - ERROR - something bad!