在Python中,time()返回的epoch time总是从1970年1月1日开始计算的吗?

2024-04-26 21:22:16 发布

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

Python中的epoch开始时间是否独立于平台(即总是1/1/1970)?

还是依赖于平台?

我想在运行Python的各种机器上序列化日期时间(具有第二精度),并且能够在不同的平台上读回它们,也可能使用不同的编程语言(而不是Python)。将纪元时间序列化是个好主意吗?


Tags: 机器序列化时间精度平台编程语言主意epoch
3条回答

time()总是返回epoch的时间,看看documentation

请注意,Epoch始终是自1970年以来的秒数,但由于不同机器上的时钟不一样,您可能会遇到一些问题。

引用:

The epoch is the point where the time starts. On January 1st of that year, at 0 hours, the “time since the epoch” is zero. For Unix, the epoch is 1970. To find out what the epoch is, look at gmtime(0).

以及:

time.time()¶

Return the time in seconds since the epoch as a floating point number. Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.

(均来自Python文档)。

Epoch time(unix time)是一个标准术语:

http://en.wikipedia.org/wiki/Unix_time

Unix time, or POSIX time, is a system for describing instances in time, defined as the number of seconds that have elapsed since midnight Coordinated Universal Time (UTC), 1 January 1970,[note 1] not counting leap seconds.[note 2] It is used widely in Unix-like and many other operating systems and file formats. It is neither a linear representation of time nor a true representation of UTC.[note 3] Unix time may be checked on some Unix systems by typing date +%s on the command line

这意味着,如果您通过Python使用epoch时间,那么跨平台的epoch时间将是一致的。一致性的最佳选择是在所有情况下都使用UTC。

The documentation说:

To find out what the epoch is, look at gmtime(0).

我认为这意味着没有特定的时代是可以保证的。

另请参见this Python-Dev thread。这似乎证实了这样一个概念,即在实践中,历元总是假定为1970/01/01,但这并没有得到语言的明确保证。

其结果是,至少对于Python来说,使用epoch time可能没问题,除非您处理的是奇怪和晦涩的平台。对于使用非Python工具进行阅读,您可能也可以,但是为了确保您需要阅读这些工具提供的文档。

相关问题 更多 >