gpt4 book ai didi

python - 带有毫秒或微秒和时区偏移的日期时间

转载 作者:行者123 更新时间:2023-11-30 22:38:13 24 4
gpt4 key购买 nike

这是日期所需的表示形式:

>>> tz = pytz.timezone('US/Central')
>>> datefmt = '%Y-%m-%d %H:%M:%S.%f%z(%Z)'
>>> datetime.now(tz).strftime(datefmt)
'2017-04-27 15:09:59.606921-0500(CDT)'

这是它的记录方式(Linux 上的 Python 3.6.0):

>>> logrecord_format = '%(asctime)s %(levelname)s %(message)s'
>>> logging.basicConfig(format=logrecord_format, datefmt=datefmt)
>>> logging.error('ruh-roh!')
2017-04-27 15:10:35.%f-0500(CDT) ERROR ruh-roh!

它没有正确填充微秒。我尝试更改 logrecord_format其他一些事情,但我无法弄清楚 - 如何配置记录器以正确的方式显示微秒和时区以匹配 strftime输出准确吗?

<小时/>

编辑:我可以接受带有偏移量的毫秒,即 2017-04-27 15:09:59,606-0500(CDT) 。那可能吗? logging提供%(msecs)03d指令,但我似乎无法让时区偏移量出现在毫秒之后。

最佳答案

就我个人而言,我没有将时区集成到日期格式中,而是直接将其添加到记录的消息格式中。通常,时区在程序执行过程中不应改变。

import logging
import time

tz = time.strftime('%z')
fmt = '%(asctime)s' + tz + ' %(levelname)s %(message)s'

logging.basicConfig(format=fmt)

logging.error("This is an error message.")

# 2017-07-28 19:34:53,336+0200 ERROR This is an error message.

关于python - 带有毫秒或微秒和时区偏移的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43667155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com