gpt4 book ai didi

python - 使用自 UNIX 纪元以来的秒数作为日志记录中的日期格式

转载 作者:太空宇宙 更新时间:2023-11-03 23:58:02 24 4
gpt4 key购买 nike

logging.basicConfig 的文档说:

datefmt - Use the specified date/time format, as accepted by time.strftime().

但是,如果我查看 time.strftime() 的文档, 那里甚至没有提到 UNIX 纪元时间戳。


更新:如果我按照 strftime(3) 的联机帮助页中的描述使用 %s ,它适用于 Linux,但不适用于 Windows。

import time
time.strftime('%s')

结果

ValueError: Invalid format string

所以我正在寻找一种独立于平台的方法来使用自 UNIX 纪元以来的秒数作为日志记录中的日期格式。

最佳答案

肯定不可能用 asctime 做到这一点,因为 strftime 关于支持的格式字符串的行为是平台相关的。

在“strftime()strptime() 行为”部分的文档中有一段是关于此的:

The full set of format codes supported varies across platforms, because Python calls the platform C library’s strftime() function, and platform variations are common. To see the full set of format codes supported on your platform, consult the strftime(3) documentation.

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior


但是,忽略 asctime,您仍然可以在 logginng 格式字符串中使用自 UNIX 纪元以来的秒数。还有一个名为 created 的属性:

%(created)f - Time when the LogRecord was created (as returned by time.time()).

https://docs.python.org/3/library/logging.html#logrecord-attributes

由于 time.time() 可在 Linux 和 Windows 上运行,因此您可以在日志格式字符串中使用 created 而不是 asctime .

关于python - 使用自 UNIX 纪元以来的秒数作为日志记录中的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56827541/

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