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

Does time.time() in the Python time module return the system's time or the time in UTC?

This question is related to python time timezone

The answer is


time.time() return the unix timestamp. you could use datetime library to get local time or UTC time.

import datetime

local_time = datetime.datetime.now()
print(local_time.strftime('%Y%m%d %H%M%S'))

utc_time = datetime.datetime.utcnow() 
print(utc_time.strftime('%Y%m%d %H%M%S'))

timestamp is always time in utc, but when you call datetime.datetime.fromtimestamp it returns you time in your local timezone corresponding to this timestamp, so result depend of your locale.

>>> import time, datetime

>>> time.time()
1564494136.0434234

>>> datetime.datetime.now()
datetime.datetime(2019, 7, 30, 16, 42, 3, 899179)
>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2019, 7, 30, 16, 43, 12, 4610)

There exist nice library arrow with different behaviour. In same case it returns you time object with UTC timezone.

>>> import arrow
>>> arrow.now()
<Arrow [2019-07-30T16:43:27.868760+03:00]>
>>> arrow.get(time.time())
<Arrow [2019-07-30T13:43:56.565342+00:00]>

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 ts
2015-04-21 12:02:19.209915
>>> print tf
2015-04-21 12:02:30.449895
>>> print te
0:00:11.239980

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

    from datetime import datetime
    
    utc_dt = datetime.utcfromtimestamp(timestamp)
    

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.

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

At least that's the concept.


To get a local timestamp using datetime library, Python 3.x

#wanted format: year-month-day hour:minute:seconds

from datetime import datetime

# get time now
dt = datetime.now()
# format it to a string
timeStamp = dt.strftime('%Y-%m-%d %H:%M:%S')

# print it to screen
print(timeStamp)

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. So time.time() returns the number of seconds since the epoch.


I eventually settled for:

>>> import time
>>> time.mktime(time.gmtime())
1509467455.0

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to time

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object

Examples related to timezone

How to set the timezone in Django? How to convert Moment.js date to users local timezone? What does this format means T00:00:00.000Z? How do I get the current timezone name in Postgres 9.3? MySQL JDBC Driver 5.1.33 - Time Zone Issue Python get current time in right timezone Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings PHP date() with timezone? How to store a datetime in MySQL with timezone info Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST