How do I get the UTC time, i.e. milliseconds since Unix epoch on Jan 1, 1970?
-
3related: [Python: How to get a value of datetime.today() that is “timezone aware”?](http://stackoverflow.com/q/4530069/4279) – jfs Dec 05 '15 at 16:41
8 Answers
For Python 2 code, use datetime.utcnow()
:
from datetime import datetime
datetime.utcnow()
For Python 3, use datetime.now(timezone.utc)
(the 2.x solution will technically work, but has a giant warning in the 3.x docs):
from datetime import datetime, timezone
datetime.now(timezone.utc)
For your purposes when you need to calculate an amount of time spent between two dates all that you need is to subtract end and start dates. The results of such subtraction is a timedelta
object.
From the python docs:
class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
And this means that by default you can get any of the fields mentioned in it's definition - days, seconds, microseconds, milliseconds, minutes, hours, weeks. Also timedelta instance has total_seconds() method that:
Return the total number of seconds contained in the duration. Equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 106) / 106 computed with true division enabled.

- 49,297
- 16
- 112
- 153

- 27,895
- 4
- 34
- 52
-
32possibly nasty surprise about datetime.utcnow() is that is does not return a timezone-aware object despite the name. This is in my opinion a big problem, which is why I prefer my answer below. See "datetime objects with no timezone should be considered as a "bug" in the application." https://julien.danjou.info/python-and-timezones/ – Tim Richardson Nov 29 '19 at 22:50
-
4The concept of a so called naive datetime object (i.e., no timezone information is set) does serve a purpose: I want my alarm clock to ring at 06:00:00 every day no matter where in the world I am. Also it allows for "virtual clocks" in say computer games: It is now 5 pm in my fantasy world. Forcing a timezone onto the datetime object would be awkward, especially with timedelta arithmetics. – DustByte Feb 06 '20 at 09:55
Timezone-aware datetime
object, unlike datetime.utcnow()
:
from datetime import datetime,timezone
now_utc = datetime.now(timezone.utc)
Timestamp in milliseconds since Unix epoch:
datetime.now(timezone.utc).timestamp() * 1000

- 24,552
- 19
- 101
- 135

- 6,608
- 6
- 44
- 71
-
35According to the Python 3 documentation this is the recommended way to do it. – roskakori Dec 04 '19 at 08:37
-
4
-
5@Marry35 yes, this should be the preferred way NOW. When the question was first asked `timezone.utc` did not exist. – Mark Ransom Nov 17 '20 at 04:48
-
4And if you prefer to have the local time (e.g. for easier display to user) but still be timezone-safe, you can use `datetime.now().astimezone()` – Martin Cejp Feb 28 '21 at 12:53
In the form closest to your original:
import datetime
def UtcNow():
now = datetime.datetime.utcnow()
return now
If you need to know the number of seconds from 1970-01-01 rather than a native Python datetime
, use this instead:
return (now - datetime.datetime(1970, 1, 1)).total_seconds()
Python has naming conventions that are at odds with what you might be used to in Javascript, see PEP 8. Also, a function that simply returns the result of another function is rather silly; if it's just a matter of making it more accessible, you can create another name for a function by simply assigning it. The first example above could be replaced with:
utc_now = datetime.datetime.utcnow
All of the above is now considered obsolete. Python 3.2 introduced datetime.timezone
so that a proper tzinfo
for UTC could be available to all. So the modern version becomes:
def utc_now():
return datetime.datetime.now(tz=datetime.timezone.utc)

- 299,747
- 42
- 398
- 622
-
1@J.F.Sebastian true, but see the comment I made earlier - this is the form closest to the code in the question. No need to confuse people by introducing tangents to their question, unless it's relevant. – Mark Ransom Aug 22 '16 at 12:18
-
There is no reason to promote bad practice without an explicit disclaimer in the answer. I've upvoted your answer but it deserves a comment that shows how it is done idiomatically in Python. Though my comment doesn't follow pep-8 naming convention, to preserve the link with the name used in the question. – jfs Aug 22 '16 at 12:24
-
2`(now - datetime.datetime(1970, 1, 1)).total_seconds()` ... What about just `time.time()`? – Chris Oct 23 '16 at 14:03
-
To get the timestamp you either use: - time.time() - cast to into to remove miliseconds simply. - int(datetime.datetime.nowutc("%s")) - returns a string, so thats why I cast to int – hectorcanto Mar 21 '17 at 17:07
-
1datetime.datetime.utcnow() does not return a timezone-aware datetime, which is really not a good idea, it's just a question of time before one eventually discovers how horrible that is. – Tim Richardson Nov 29 '19 at 22:52
-
1@TimRichardson I don't disagree, but at the time this answer was written there was no alternative - Python didn't include any `tzinfo` objects, even for UTC. – Mark Ransom Nov 30 '19 at 01:38
-
`ruff check src`: DTZ003 The use of `datetime.datetime.utcnow()` is not allowed, use `datetime.datetime.now(tz=)` instead. https://beta.ruff.rs/docs/rules/#flake8-datetimez-dtz – NeilG Aug 02 '23 at 23:51
import datetime
import pytz
# datetime object with timezone awareness:
datetime.datetime.now(tz=pytz.utc)
# seconds from epoch:
datetime.datetime.now(tz=pytz.utc).timestamp()
# ms from epoch:
int(datetime.datetime.now(tz=pytz.utc).timestamp() * 1000)

- 5,385
- 42
- 41
-
pytz is deprecated now that the zoneinfo DB/package has been moved into the Std Lib. – Marc Jun 30 '22 at 15:12
-
Timezone aware with zero external dependencies:
from datetime import datetime, timezone
def utc_now():
return datetime.utcnow().replace(tzinfo=timezone.utc)

- 18,659
- 11
- 66
- 69
-
1inorder to print it in zulu format, this is the way to go ```datetime.utcnow().replace(tzinfo=timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')``` – Imtiaz Shakil Siddique Jun 17 '21 at 14:37
-
1How is it different from `datetime.now(timezone.utc)`? Just curious. cause I believe the result is exactly the same. – Gagan Deep Singh Mar 06 '22 at 19:23
-
1@GaganDeepSingh Both give the exact same `datetime` object. (There are sometimes multiple paths to the same destination.) `.replace(tzinfo=timezone.utc)` merely sets the `.tzinfo` member which is unfortunately `None` by default. – Mateen Ulhaq May 31 '22 at 07:53
From datetime.datetime you already can export to timestamps with method strftime. Following your function example:
import datetime
def UtcNow():
now = datetime.datetime.utcnow()
return int(now.strftime("%s"))
If you want microseconds, you need to change the export string and cast to float like: return float(now.strftime("%s.%f"))

- 1
- 1

- 1,987
- 15
- 18
-
1What's the point of converting to a string and then back to a number when you can get the number directly? – Mark Ransom Mar 21 '17 at 18:09
-
The point is that you may want to change things on the function and for that reason is better stick to datetime object, not using `time.time()`, You could also use time.mktime(now.timetuple()) to convert directly to int. Anyway, for this simple case `time.time()` is also a valid option. What I find odd, is going by timedelta to find the seconds. – hectorcanto Mar 22 '17 at 11:50
-
Note, that `strftime("%s")` is platform dependent and does not work on Windows. (At least it doesn't for me on Windows 10). – Julian Kirsch Dec 31 '19 at 02:21
you could use datetime
library to get UTC time even local time.
import datetime
utc_time = datetime.datetime.utcnow()
print(utc_time.strftime('%Y%m%d %H%M%S'))

- 103
- 1
- 5
-
What does this 2021 answer add to the conversation? It's the same method as shown in the accepted answer from almost 10 years earlier. – wim Oct 23 '22 at 02:56
why all reply based on datetime and not time? i think is the easy way !
import time
nowgmt = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
print(nowgmt)

- 87
- 1
- 2
-
nowgmt will be a string, which is less flexible than having a datetime object – sezanzeb Sep 02 '21 at 16:46