Knot
Knot

Reputation: 141

Difference between time.time() and datetime.utcnow()

I want to know about the difference between time.time() and datetime.datetime.utcnow(). Does both returns the current UTC time?

Upvotes: 1

Views: 2826

Answers (2)

user3980558
user3980558

Reputation:

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. You can read more about time here.

Regarding datetime, datetime.datetime.utcnow() returns the current UTC date and time, with tzinfo None. This is like now(), but returns the current UTC date and time, as a naive datetime object. An aware current UTC datetime can be obtained by calling datetime.now(timezone.utc)

Here is some sample output I ran on my computer, converting it to a string as well:

>>> import time
>>> ts = time.time()
>>> print(ts)
1583748843.6486485
>>> import datetime
>>> st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
>>> print(st)
2020-03-09 12:14:03

Upvotes: 5

h4z3
h4z3

Reputation: 5468

Does both returns the current UTC time?

Yes and no.

The thing is how they return it.

Module datetime and classes in it (including datetime as class, which you use here) are for operating on date and time - thus they store the date/time in a structured form (object) and allow operations on it (methods).

>>> import datetime
>>> datetime.datetime.utcnow()
datetime.datetime(2020, 3, 9, 10, 4, 4, 284553)

While time module is more about straight C-like time operations. In this case: just returning timestamp (seconds from epoch) - as float (not a special class object).

>>> import time
>>> time.time()
1583748064.798787

Upvotes: 4

Related Questions