Does Python's time.time() return the local or UTC timestamp? Does Python's time.time() return the local or UTC timestamp? python python

Does Python's time.time() return the local or UTC timestamp?


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.

Python 2.7.3 (default, Apr 24 2012, 00:00:54) [GCC 4.7.0 20120414 (prerelease)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import time>>> ts = time.time()>>> print ts1355563265.81>>> import datetime>>> st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')>>> print st2012-12-15 01:21:05>>>

The ts variable is the time returned in seconds. I then converted it to a string using the datetime 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 the datetime.datetime:

>>> import datetime>>> print datetime.datetime.utcnow()2012-12-15 10:14:51.898000

The now differs from utcnow as expected -- otherwise they work the same way:

>>> print datetime.datetime.now()2012-12-15 11:15:09.205000

You can render the timestamp to the string explicitly:

>>> str(datetime.datetime.now())'2012-12-15 11:15:24.984000'

Or you can be even more explicit to format the timestamp the way you like:

>>> datetime.datetime.now().strftime("%A, %d. %B %Y %I:%M%p")'Saturday, 15. December 2012 11:19AM'

If you want the ISO format, use the .isoformat() method of the object:

>>> datetime.datetime.now().isoformat()'2013-11-18T08:18:31.809000'

You can use these in variables for calculations and printing without conversions.

>>> ts = datetime.datetime.now()>>> tf = datetime.datetime.now()>>> te = tf - ts>>> print ts2015-04-21 12:02:19.209915>>> print tf2015-04-21 12:02:30.449895>>> print te0:00:11.239980


Based on the answer from #squiguy, to get a true timestamp I would type cast it from float.

>>> import time>>> ts = int(time.time())>>> print(ts)1389177318

At least that's the concept.


matomo