如何记录时区
%Z 来自strftime 格式
窗户
>>> import logging
>>> logging.basicConfig(format="%(asctime)s %(message)s", datefmt="%m/%d/%Y %I:%M:%S %p %Z")
>>> logging.error('test')
11/03/2017 02:29:54 PM Mountain Daylight Time test
Linux
>>> import logging
>>> logging.basicConfig(format="%(asctime)s %(message)s", datefmt="%m/%d/%Y %I:%M:%S %p %Z")
>>> logging.error('test')
11/03/2017 02:30:50 PM MDT test
如果问题是
我如何登录与服务器本地时间不同的时区?
部分答案是logging.Formatter.converter,但是,您必须了解幼稚和有意识的datetime 对象。除非您想编写自己的时区模块,否则我强烈建议您使用 pytz 库 (pip install pytz)。 Python 3 包括一个 UTC 和 UTC 偏移时区,但是对于夏令时或其他偏移,您必须实施一些规则,所以我建议使用 pytz 库,即使对于 python 3 也是如此。
例如,
>>> import datetime
>>> utc_now = datetime.datetime.utcnow()
>>> utc_now.isoformat()
'2019-05-21T02:30:09.422638'
>>> utc_now.tzinfo
(None)
如果我对这个 datetime 对象应用时区,时间不会改变(或者会为 ValueError)。
>>> mst_now = utc_now.astimezone(pytz.timezone('America/Denver'))
>>> mst_now.isoformat()
'2019-05-21T02:30:09.422638-06:00'
>>> utc_now.isoformat()
'2019-05-21T02:30:09.422638'
但是,如果相反,我会这样做
>>> import pytz
>>> utc_now = datetime.datetime.now(tz=pytz.timezone('UTC'))
>>> utc_now.tzinfo
<UTC>
现在我们可以在我们希望的任何时区创建一个正确翻译的datetime 对象
>>> mst_now = utc_now.astimezone(pytz.timezone('America/Denver'))
>>> mst_now.isoformat()
'2019-05-20T20:31:44.913939-06:00'
啊哈!现在将其应用于日志记录模块。
Epoch 时间戳到带有时区的字符串表示
LogRecord.created 属性设置为time 模块创建LogRecord 的时间(由time.time() 返回)。这将返回一个时间戳 (seconds since the epoch)。您可以自己翻译到给定的时区,但我还是建议pytz,通过覆盖转换器。
import datetime
import logging
import pytz
class Formatter(logging.Formatter):
"""override logging.Formatter to use an aware datetime object"""
def converter(self, timestamp):
dt = datetime.datetime.fromtimestamp(timestamp)
tzinfo = pytz.timezone('America/Denver')
return tzinfo.localize(dt)
def formatTime(self, record, datefmt=None):
dt = self.converter(record.created)
if datefmt:
s = dt.strftime(datefmt)
else:
try:
s = dt.isoformat(timespec='milliseconds')
except TypeError:
s = dt.isoformat()
return s
Python 3.5、2.7
>>> logger = logging.root
>>> handler = logging.StreamHandler()
>>> handler.setFormatter(Formatter("%(asctime)s %(message)s"))
>>> logger.addHandler(handler)
>>> logger.setLevel(logging.DEBUG)
>>> logger.debug('test')
2019-05-20T22:25:10.758782-06:00 test
Python 3.7
>>> logger = logging.root
>>> handler = logging.StreamHandler()
>>> handler.setFormatter(Formatter("%(asctime)s %(message)s"))
>>> logger.addHandler(handler)
>>> logger.setLevel(logging.DEBUG)
>>> logger.debug('test')
2019-05-20T22:29:21.678-06:00 test
用America/Anchorage 替换America/Denver 来代替pytz 定义的posix 时区
>>> next(_ for _ in pytz.common_timezones if 'Alaska' in _)
'US/Alaska'
US/Alaska is deprecated
>>> [_ for _ in pytz.all_timezones if 'Anchorage' in _]
['America/Anchorage']
本地
如果您在寻找如何记录本地时区时遇到此问题和答案,则不要硬编码时区,而是获取 tzlocal (pip install tzlocal) 并替换
tzinfo = pytz.timezone('America/Denver')
与
tzinfo = tzlocal.get_localzone()
现在它可以在运行脚本的任何服务器上运行,服务器上的时区。
不记录 UTC 时的警告
我应该补充一点,根据应用程序,登录本地时区可能会产生歧义或至少每年两次造成混淆,其中跳过凌晨 2 点或重复凌晨 1 点,可能还有其他时间。