Does Python's time.time() return a timestamp in UTC? [duplicate]

人盡茶涼 提交于 2020-01-10 08:52:10

问题


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?


回答1:


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.)




回答2:


time.time() returns seconds since epoch, so it doesn't define which time standard or zone is being used.

Convert to time standards using:

  • time.localtime([secs]) - Local time as defined by your operating system
  • time.gmtime([secs]) - UTC

They both return a time.struct_time.

>>> t = time.time()
>>> time.localtime(t)
time.struct_time(tm_year=2013, tm_mon=5, tm_mday=15, tm_hour=2, tm_min=41, tm_sec=49, tm_wday=2, tm_yday=135, tm_isdst=1)
>>> time.gmtime(t)
time.struct_time(tm_year=2013, tm_mon=5, tm_mday=15, tm_hour=0, tm_min=41, tm_sec=49, tm_wday=2, tm_yday=135, tm_isdst=0)


来源:https://stackoverflow.com/questions/16554887/does-pythons-time-time-return-a-timestamp-in-utc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!