Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

time

utc

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?

like image 314
incognito2 Avatar asked May 15 '13 00:05

incognito2


2 Answers

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

like image 99
abarnert Avatar answered Sep 25 '22 15:09

abarnert


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)
like image 33
timss Avatar answered Sep 21 '22 15:09

timss