使用自 UNIX 纪元以来的秒数作为日志记录中的日期格式
Use number of seconds since the UNIX Epoch as date format in logging
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
关于支持的格式字符串的行为是 platform-dependent.
在“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
。
无法使用 ANSI C 中的 strftime()
获得 Unix 纪元格式(毕竟,这是一种输入)。
同样,您不能将此功能作为 cross-platform in Python.
但是,您可以利用 non-special 个字符在 C 和 Python 中都通过 strftime()
的事实。
因此,您可以使用以下 - 诚然非常丑陋但有效 - 解决方法:
import time
time.strftime(str(time.time()))
或更准确地说:
time.strftime(str(int(time.time())))
time.strftime(str(int(time.time()))) == time.strftime('%s')
# True
logging.basicConfig
的文档说:
datefmt
- Use the specified date/time format, as accepted bytime.strftime()
.
但是,如果我查看 time.strftime()
的文档,那里甚至都没有提到 UNIX 纪元时间戳。
更新: 如果我按照 strftime(3)
联机帮助页中的描述使用 %s
,它可以与 Linux 一起使用,但不能Windows.
import time
time.strftime('%s')
结果
ValueError: Invalid format string
所以我正在寻找一种独立于平台的方法来使用自 UNIX 纪元以来的秒数作为日志记录中的日期格式。
肯定无法使用 asctime
执行此操作,因为 strftime
关于支持的格式字符串的行为是 platform-dependent.
在“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 bytime.time()
).
https://docs.python.org/3/library/logging.html#logrecord-attributes
由于 time.time()
适用于 Linux 和 Windows,您可以在日志格式字符串中使用 created
而不是 asctime
。
无法使用 ANSI C 中的 strftime()
获得 Unix 纪元格式(毕竟,这是一种输入)。
同样,您不能将此功能作为 cross-platform in Python.
但是,您可以利用 non-special 个字符在 C 和 Python 中都通过 strftime()
的事实。
因此,您可以使用以下 - 诚然非常丑陋但有效 - 解决方法:
import time
time.strftime(str(time.time()))
或更准确地说:
time.strftime(str(int(time.time())))
time.strftime(str(int(time.time()))) == time.strftime('%s')
# True