在日志记录中使用UNIX Epoch之后的秒数作为日期格式

2024-09-28 17:26:46 发布

您现在位置:Python中文网/ 问答频道 /正文

^{}的文档说:

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

但是,如果我看一下^{}的文档,这里甚至没有提到UNIX Epoch时间戳。你知道吗


更新:如果我使用的是%s,如^{}手册页中所述,它适用于Linux,但不适用于Windows。你知道吗

import time
time.strftime('%s')

结果

ValueError: Invalid format string

因此,我正在寻找一种独立于平台的方法来使用UNIX时代以来的秒数作为日志记录中的日期格式。你知道吗


Tags: the文档formatdatebytimeuseas
2条回答

当然,用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,您仍然可以在日志格式字符串中使用UNIX Epoch之后的秒数。还有另一个名为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。你知道吗

Unix epoch格式不能使用ansic中的strftime()获得(毕竟,这是一种输入)。 类似地,在Python中,不能将此功能作为跨平台的功能。你知道吗

但是,可以利用非特殊字符在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

相关问题 更多 >