Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does python's time.time() method work?

The time.time() method provides you the timestamp which is basically the time elapsed since epoch(which is in UTC).

The datetime.fromtimestamp() states that if the tz param isn't provided then a local datetime object is returned.

I am aware that the tz info is basically treated as an offset to utc in order to get the local time.

If that's the case, the current time in utc had to be extracted from the platform.

How is the current time of the day, be it local or UTC, extracted from the underlying platform?

like image 995
farthVader Avatar asked Jan 07 '15 23:01

farthVader


1 Answers

In (the current) CPython time.time() calls
floattime(NULL) which calls
_PyTime_gettimeofday_info() which calls
pygettimeofday()
where pygettimeofday() may use GetSystemTimeAsFileTime(), clock_gettime(CLOCK_REALTIME), gettimeofday() functions depending on the platform.


Unrelated: time.time() returns "seconds since the epoch". It is POSIX time on most systems supported by Python (Linux, OS X, Windows). POSIX timestamp is not the number of elapsed SI seconds since 1970-01-01T00:00:00Z (Epoch). Though it is very close (within 0.000003% counting from Epoch). It counts the number of non-leap SI seconds or the number of UT1 (mean-solar) seconds.

UTC is not a linear time scale relative to TAI, GPS time scales (see the picture). You won't get the exact elapsed SI seconds due to leap seconds (UTC is kept within ±0.9 seconds of UT1 (Earth rotation)). See also, Is a day always 86,400 epoch seconds long?

Some OSes can be configured to use non-POSIX "right" zoneinfo. time.time() is not required to return POSIX timestamp in this case. "right" timezone counts leap seconds and therefore the difference between "right" timestamps and POSIX timestamps is not constant e.g., it will increase in July 2015 due to the introduction of the positive leap second.

In principle, "the epoch" may differ from POSIX Epoch, though Python doesn't support such systems.

like image 154
jfs Avatar answered Nov 12 '22 22:11

jfs