How do I get the UTC time, i.e. milliseconds since Unix epoch on Jan 1, 1970?
9 Answers
For Python 3, use datetime.now(timezone.utc) to get a timezone-aware datetime, and use .timestamp() to convert it to a timestamp.
from datetime import datetime, timezone datetime.now(timezone.utc) datetime.now(timezone.utc).timestamp() * 1000 # POSIX timestamp in milliseconds 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.
For Python 2 (the 2.x solution will technically work, but has a giant warning in the 3.x docs), you would have used datetime.utcnow():
from datetime import datetime datetime.utcnow() 4 Comments
datetime.now(timezone.utc)from datetime import UTC, datetime datetime.now(UTC)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 4 Comments
timezone.utc did not exist.datetime.now().astimezone()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) 7 Comments
(now - datetime.datetime(1970, 1, 1)).total_seconds() ... What about just time.time()?tzinfo objects, even for UTC.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) Timezone aware with zero external dependencies:
from datetime import datetime, timezone def utc_now(): return datetime.utcnow().replace(tzinfo=timezone.utc) 4 Comments
datetime.utcnow().replace(tzinfo=timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')datetime.now(timezone.utc)? Just curious. cause I believe the result is exactly the 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.datetime.utcnow() is deprecated in Python 3.12, use another answer instead.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"))
3 Comments
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.strftime("%s") is platform dependent and does not work on Windows. (At least it doesn't for me on Windows 10).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')) 1 Comment
As datetime.datetime.utcnow() is deprecated, you can alternatively use the below code to get the time in UTC.
from datetime import datetime, timezone datetime.now(timezone.utc) 1 Comment
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) 3 Comments
datetime.datetime.now() uses time.time(). With this knowledge this question boils down to the question of should we use time.time() ... As explained in this answer...