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

- 347,512
- 102
- 1,199
- 985

- 9,430
- 10
- 39
- 50
-
111Timestamps don't have timezones. They represent a number of seconds since the epoch. The epoch is a specific moment in time which doesn't depend on the timezone. – jwg Jan 29 '16 at 09:48
-
7@jwg: the commonly used POSIX timestamps do not count leap seconds and therefore they are not the "number of [elapsed SI] seconds since the epoch" (they are close). – jfs Feb 16 '17 at 06:54
-
9I don't think this is an accurate objection @J.F.Sebastian. Leap seconds are not 'elapsed seconds since the epoch'. They are changes in the time representations recorded by clocks which do not correspond to elapsed seconds. – jwg Feb 20 '17 at 09:08
-
2@jwg "they" is obviously "timestamps" in my comment (as well as in your first comment), not "leap seconds" (otherwise it makes no sense). – jfs Feb 20 '17 at 09:50
-
4@J.F.Sebastian Sorry for the confusion. Leap seconds are not 'elapsed seconds'. Therefore timestamps, which are 'numbers of elapsed seconds', do not and should not include leap seconds. – jwg Feb 20 '17 at 11:38
-
6@jwg wrong. You can't erase physical time. POSIX timestamp is not the number of elapsed SI seconds. Here's an example: 3 seconds elapsed between "December 31, 2016 at 6:59:59pm" and "December 31, 2016 at 7:00:01pm" in New York but the difference in the corresponding POSIX timestamps is only 2 seconds (the leap second is not counted). – jfs Feb 20 '17 at 12:22
9 Answers
The time.time()
function returns the number of seconds since the epoch, as a float. 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 on Earth 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.
>>> import time
>>> ts = time.time()
>>> ts
1355563265.81
>>> import datetime
>>> datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
'2012-12-15 01:21:05'
>>>
The ts
variable is the time returned in seconds. I then converted it to a human-readable string using the datetime
library.

- 14,854
- 11
- 100
- 103

- 32,370
- 6
- 56
- 63
-
Thanks so much...it was really helpful. I thought so that it returned in UTC, but couldn't be sure. Thanks – Saransh Mohapatra Dec 15 '12 at 12:04
-
81Why should we `import time` when datetime basically gives you timestamp. Just remove the milliseconds - `str(datetime.datetime.now()).split('.')[0]` – Hussain Jan 03 '13 at 13:25
-
18@Alexis Unix epoch is defined pretty clearly [here](http://www.epochconverter.com/). It even points out a Python example a ways down the page. I don't understand your comment. – squiguy Oct 31 '13 at 22:38
-
9@squiguy to be honest I don't remember what made me say that. I must have misread something, and I was struggling to find why some tests were breaking while I moved between France and US to finally find that the issue was because of DST that makes the week longer in this period of the year. Sorry about that and thank you for pointing this out. – Alexis Nov 01 '13 at 18:57
-
6it is not *"seconds in UTC."*. [The timestamp returned by `time.time()` is not in any timezone](http://stackoverflow.com/a/20035913/4279). "seconds since the epoch" is a term; it is not *elapsed* seconds since some point in time (epoch). You can *convert* it to your local time (with tz database) and/or UTC timezone easily. btw, if you drop `.strftime()` the result is (almost) the same (+/- microseconds). – jfs Sep 04 '14 at 16:56
-
1
-
2@Alexis is absolutely right: use `time.gmtime()` to get UTC, The comment is easy to understand: datetime.fromtimestamp returns the **local** time, not the UTC time – Oct 06 '16 at 11:59
-
1@Hussain `int(datetime.datetime.now())` should be a lot faster than converting to a string just to get rid of the fractional parts. – Alexander Oh Oct 07 '16 at 15:23
-
5just tested it, time.time() does not give UTC time, it gives my local zone time – sliders_alpha Jun 08 '17 at 18:17
-
To get just the timestamp ```import time``` and run ```str(time.time()).split(".")[0]```. Fixing @Hussain comment – Hemã Vidal Mar 28 '18 at 12:55
-
5`datetime.utcfromtimestamp(ts)` creates a *naive* datetime in the UTC time zone. Unless your system time is UTC, it will be WRONG. (Most of the code in datetime module treats naive datetimes as local time.) Instead use `datetime.fromtimestamp(ts,datetime.timezone.utc)` which creates a *timezone aware* datetime in the UTC time zone. – Terrel Shumway Jul 14 '19 at 04:27
-
@sliders_alpha just tested it, time.time() gives a timestamp which can be converted to UTC or to any other time zone. – Alexandr Zarubkin Apr 04 '23 at 09:14
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

- 13,558
- 21
- 105
- 181

- 20,112
- 15
- 76
- 139
-
2I wanted the epoch time....not in date format...as was evident from my mention of command time.time() – Saransh Mohapatra Dec 15 '12 at 12:03
-
39OK, no problem. Someone else may need *timestamp* say for placing in text files. – pepr Dec 15 '12 at 17:34
-
1I am another one, redirected here likely due to the *unreasonable* number of upvotes. The question is malformed and the accepted answer misleading for the typical need: getting a human readable suffix - say for filenames - in the most used server timezone. – Oct 06 '16 at 21:39
-
To print a timestamp as part of a string, use this: Python2: `import datetime; print "%s: My timestamp message" % datetime.datetime.utcnow()` Python3: `import datetime; print ("%s: My timestamp message" % datetime.datetime.utcnow())` – Mr-IDE Nov 08 '17 at 10:29
-
2`datetime.datetime.utcnow()` is evil. It creates a naive datetime that is not local time. Unless your local time is UTC, it will be WRONG. Use `datetime.datetime.now(datetime.timezone.utc)` instead. This creates a timezone aware datetime representing the current time. – Terrel Shumway Jul 14 '19 at 04:04
-
@TerrelShumway: I cannot corfirm that. My local time is not UTC, and the result is correct. It may depend on the OS and the OS settings of the time. It may also depend on the (old) Python version -- if there was a bug in the past. Can you better describe your situation and to show what is wrong? – pepr Jul 15 '19 at 09:35
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.

- 13,687
- 5
- 58
- 74

- 4,417
- 5
- 21
- 30
-
1What's the reason for typecasting the timestamp? What's the type by default? – Tizzee Dec 04 '13 at 09:46
-
4
-
4But if you need more precise time than in seconds, the float makes sense. – pepr Feb 05 '14 at 20:30
-
May I know, is it possible to have int overflow? Should we use `ts = long(time.time())` ? – Cheok Yan Cheng Jul 17 '15 at 15:02
-
One of Python's big pulls is that it automatically switches the underlying type without you having to be too strict. http://stackoverflow.com/questions/7604966/maximum-and-minimum-values-for-ints http://stackoverflow.com/a/7604981/2080324 – Rudi Strydom Jul 17 '15 at 20:59
-
@CheokYanCheng I wouldn't worry too much about it, Python should do this seamlessly for you: http://stackoverflow.com/a/2104947/2080324. Otherwise you would use a language which is more strongly type ie: Java, Go – Rudi Strydom Jul 17 '15 at 21:02
-
3@RudiStrydom: Python is strongly typed. Don't confuse it with being staticly typed. – jfs Aug 14 '15 at 22:36
-
1@CheokYanCheng: `int()` is polymorphic. It would return `long` if necessary on old Python versions -- all integers are long on new Python versions. – jfs Aug 14 '15 at 22:38
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?
-
6This is the only answer that is correctly mentioning `datetime.utcfromtimestamp` while there are 308 upvotes on an answer with `datetime.fromtimestamp` :-( – Oct 06 '16 at 11:46
-
@TerrelShumway the question is about what the `time.time()` function returns (it is very short). Your comment addresses some other question (you've changed your comment since I've started answering it. For the worse). An aside note; the word "correct" should be used sparingly (time zones are complicated—there is no silver bullet—only trade offs for a particular use-case). – jfs Jul 12 '19 at 21:26
-
Do not use `datetime.datetime.utcfromtimestamp(ts)`. Unless your local time is UTC, it will be WRONG, because it creates a naive datetime that is not local time. Use `datetime.datetime.fromtimestamp(ts,datetime.timezone.utc)` instead. This creates a timezone aware datetime representing the same instant as the timestamp. – Terrel Shumway Jul 14 '19 at 04:13
-
Yes. My previous comment was dead wrong. Most of the code in the datetime module treat naive datetimes as local time. Using naive datetimes is like opening a text file without knowing the encoding. – Terrel Shumway Jul 14 '19 at 04:14
-
@TerrelShumway It is wrong to assume that UTC time may be used only on systems where it is the local time. It is true that some parts of stdlib treat naive datetime objects as having the local timezone (regrettably). I would prefer that `naive_dt.astimezone()` wouldn't exist like implicit `bytes.encode()` no longer exists in Python 3. It is true that it is beneficial to work with UTC time internally in many cases. There are great many things can be said about datetime module (I've answered enough questions to get a gold badge) most are out of scope for the question: what `time.time()` returns. – jfs Jul 14 '19 at 05:51
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)

- 1,147
- 13
- 13
I eventually settled for:
>>> import time
>>> time.mktime(time.gmtime())
1509467455.0

- 17,274
- 23
- 92
- 150
-
1That may satisfy your local needs, but it may be misleading to people expecting numbers in that range to be seconds since the [GMT] epoch. `time.time()` returns decimal/float like `1574115250.818733` and milliseconds-since-epoch is easily `int(time.time() * 1000)` e.g. `1574115254915` – MarkHu Nov 18 '19 at 22:14
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.

- 5,272
- 2
- 29
- 50
-
While it's true that UTC is a time *standard* and not a time zone, the standard is that it share the same time as GMT. So .... – Craig Hicks Mar 21 '19 at 06:46
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]>

- 10,057
- 7
- 56
- 88
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'))

- 103
- 1
- 5
-
`utc_time` from .utcnow() is ok as as string but dangerous as a datetime object. since it's naive, it might resemble UTC but it still ***behaves like local time*** if you do anything with it in your Python script (e.g. timedelta arithmetic). – FObersteiner Feb 07 '23 at 10:26