Python 的 time.time() 是否以 UTC 返回时间戳? [英] Does Python's time.time() return a timestamp in UTC?

查看:31
本文介绍了Python 的 time.time() 是否以 UTC 返回时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以 UTC 时间生成 UNIX 时间戳,因此我使用 time.time() 来生成它.
我还需要做其他事情吗,或者时间戳会自动以 UTC 格式显示吗?

解决方案

从技术上讲,time.time() 没有指定,实际上,至少在 CPython 中,它以底层标准 C 库的 time 函数使用的任何格式返回时间戳.

C 标准(不是免费提供的)没有说明这是否是 GMT,POSIX 标准.它只是说:

<块引用>

time() 函数应返回自 Epoch 以来的时间值(以秒为单位).

... 不说时区,除了您可以将其传递给 localtimegmtime 以获得本地或 GMT 时区的中断时间".

所以,这是特定于平台的.平台可以返回任何它想要的 time,只要它以一种使 localtimegmtime 正常工作的方式返回.>

话虽如此,通常将是 GMT,或者更确切地说,是 UTC (Windows) 或 UTC-except-for-leap-seconds(大多数其他平台).例如,FreeBSD 说:

<块引用>

time() 函数返回自 1970 年 1 月 1 日协调世界时 0 小时 0 分 0 秒以来的时间值,以秒为单位,不包括闰秒.

OS X 和大多数其他 *BSD 具有相同的联机帮助页,Windowslinux/glibc还专门返回UTC(有无闰秒)等>

此外,Python 文档说:

<块引用>

要了解时代是什么,请查看gmtime(0).

将其与 timegmtime 的定义放在一起,平台返回本地时间戳比 GMT 需要更多的工作.(话虽如此,这种说法不可能那么权威,因为对于任何 POSIX 平台来说,这实际上都不完全正确,这要归功于闰秒.)

I need to generate a UNIX timestamp in UTC time so I'm using time.time() to produce it.
Do I need to do anything else or is the timestamp automatically in UTC?

解决方案

Technically, time.time() doesn't specify, and practically, at least in CPython, it returns a timestamp in whatever format is used by the underlying standard C library's time function.

The C standard (which isn't freely available) doesn't say whether this is GMT, and neither does the POSIX standard. It just says:

The time() function shall return the value of time in seconds since the Epoch.

… without saying anything about timezone, except that you can pass it to localtime or gmtime to get a "broken-down time" in local or GMT timezones.

So, this is platform-specific. A platform can return anything it wants for time, as long as it does so in a way that makes localtime and gmtime work properly.

That being said, it's usually going to be GMT—or, rather, either UTC (Windows), or UTC-except-for-leap-seconds (most other platforms). For example, FreeBSD says:

The time() function returns the value of time in seconds since 0 hours, 0 minutes, 0 seconds, January 1, 1970, Coordinated Universal Time, without including leap seconds.

OS X and most other *BSDs have the same manpage, Windows and linux/glibc also specifically return UTC (with or without leap seconds), etc.

Also, the Python documentation says:

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

Putting that together with the definitions for time and gmtime, it would be much more work for a platform to return local timestamps than GMT. (That being said, this statement can't be all that authoritative, because it's actually not quite true for any POSIX platform, thanks to leap seconds.)

这篇关于Python 的 time.time() 是否以 UTC 返回时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆