Does time.time()
in the Python time module return the system's time or the time in UTC?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
The answer could be neither or both.
neither:
time.time()
returns approximately the number of seconds elapsed since the Epoch. The result doesn't depend on timezone so it is neither UTC nor local time. Here's POSIX defintion for "Seconds Since the Epoch".both:
time.time()
doesn't require your system's clock to be synchronized so it reflects its value (though it has nothing to do with local timezone). Different computers may get different results at the same time. On the other hand if your computer time is synchronized then it is easy to get UTC time from the timestamp (if we ignore leap seconds):On how to get timestamps from UTC time in various Python versions, see How can I get a date converted to seconds since epoch according to UTC?
Based on the answer from #squiguy, to get a true timestamp I would type cast it from float.
At least that's the concept.
The
time.time()
function returns the number of seconds since the epoch, as seconds. Note that the "epoch" is defined as the start of January 1st, 1970 in UTC. So the epoch is defined in terms of UTC and establishes a global moment in time. No matter where you are "seconds past epoch" (time.time()) returns the same value at the same moment.Here is some sample output I ran on my computer, converting it to a string as well.
The
ts
variable is the time returned in seconds. I then converted it to a string using thedatetime
library making it a string that is human readable.This is for the text form of a timestamp that can be used in your text files. (The title of the question was different in the past, so the introduction to this answer was changed to clarify how it could be interpreted as the time. [updated 2016-01-14])
You can get the timestamp as a string using the
.now()
or.utcnow()
of thedatetime.datetime
:The
now
differs fromutcnow
as expected -- otherwise they work the same way:You can render the timestamp to the string explicitly:
Or you can be even more explicit to format the timestamp the way you like:
If you want the ISO format, use the
.isoformat()
method of the object:You can use these in variables for calculations and printing without conversions.
I eventually settled for:
There is no such thing as an "epoch" in a specific timezone. The epoch is well-defined as a specific moment in time, so if you change the timezone, the time itself changes as well. Specifically, this time is
Jan 1 1970 00:00:00 UTC
. Sotime.time()
returns the number of seconds since the epoch.